5 Replies - 9526 Views - Last Post: 27 October 2015 - 01:28 PM

#1 Premier2k   User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 200
  • Joined: 26-August 08

Data binding in WPF from multiple classes

Posted 27 October 2015 - 12:11 PM

Hi all,

I've struggled to find an answer for this question, every time I find a tutorial it doesn't quite cover what I don't understand so figured I'd come here and ask.

How do I data bind to different classes?

For example I'm watching a video on Pluralsight that shows that I can databind using DataContext, this is the XAML

<Window x:Class="DataBindingOneWay.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel Name="Display">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Name: " />
                <TextBlock Margin="5,0,0,0" Text="{Binding Name}" />
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Title: " />
                <TextBlock Margin="5,0,0,0" Text="{Binding Title}" />
            </StackPanel>
            <Button Content="Change"
                    Click="Button_Click" />
        </StackPanel>
    </Grid>
</Window>


This is the code behind:

using System.Windows;

namespace DataBindingOneWay
{
    /// <summary>
    /// Interaction logic for Mainwindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Employee emp;
        public MainWindow()
        {
            InitializeComponent();
            emp = new Employee()
            {
                Name = "Joe",
                Title = "QA"
            };
            DataContext = emp;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            emp.Name = "Jesse";
            emp.Title = "Evan";
        }
    }
}


and then finally this is the Employee.cs class:

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace DataBindingOneWay
{
    public class Employee : INotifyPropertyChanged
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                onpropertychanged();
            }
        }

        private string _title;
        public string Title
        {
            get { return _title; }
            set
            {
                _title = value;
                onpropertychanged();
            }
        }

        public static Employee GetEmployee()
        {
            var emp = new Employee()
            {
                Name = "Tom",
                Title = "Developer"
            };
            return emp;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void onpropertychanged(
            [CallerMemberName] string caller = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(caller));
            }
        }
    }
}


Now that all works fine, when the button is clicked the name and title change as well. But what if I wanted to data bind from another source as well?

Let's say I have a wage field on screen and I have a payroll class. I can set a DataContext = emp; like in the example but I can't also set DataContext = payroll; because that will overwrite the first one?

So how do I databind from multiple classes? I can put {Binding wage} in to the XAML but it won't know what that is without the DataContext = payroll

Does that make sense? I can't seem to find an answer anywhere, or maybe I'm just not 'getting it'?

Premier2k

This post has been edited by Premier2k: 27 October 2015 - 12:11 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Data binding in WPF from multiple classes

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Data binding in WPF from multiple classes

Posted 27 October 2015 - 12:28 PM

Quote

How do I data bind to different classes?

You wrap them in one class that is your ViewModel.

Your different class instances are the 'models'.
The mix of them that matches a particular 'View' is the ViewModel.

For example:
In a restaraunt one view for the waiter would show just the 'Ticket' which contains a collection of 'Meal' objects.
But the 'View' for the supervisor shows more things, such as method of payment and the credit card authorization number.
So different views require different objects. Thus you make a 'ViewModel' that includes all the things needed for that particular view.

There are some WPF tutorials linked in my signature that should help.
Was This Post Helpful? 1
  • +
  • -

#3 Premier2k   User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 200
  • Joined: 26-August 08

Re: Data binding in WPF from multiple classes

Posted 27 October 2015 - 12:33 PM

Once again tlhIn`toq you've come to my rescue. I'll go through those links and have a read, hopefully it'll make more sense to me.
I keep coming across this ViewModel a lot in some of the posts I've been reading along with MVVM which I believe is model view view model. I need to go through that in-depth as well.

Many thanks again,
Premier2k
Was This Post Helpful? 0
  • +
  • -

#4 Premier2k   User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 200
  • Joined: 26-August 08

Re: Data binding in WPF from multiple classes

Posted 27 October 2015 - 12:52 PM

Something has just occurred to me, I recall seeing the data context also set in the XAML(I forget where) rather than in the code behind.

Does this mean I can set the data context differently for each component? i.e. Have a different data context for a different stackpanel?

I appreciate that wrapping them in one class in a ViewModel is probably the best way to go about this but this just suddenly popped in to my head.
Was This Post Helpful? 0
  • +
  • -

#5 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6818
  • View blog
  • Posts: 28,229
  • Joined: 12-December 12

Re: Data binding in WPF from multiple classes

Posted 27 October 2015 - 01:23 PM

DataContext can be set in the XAML but you are not changing much by doing this. It is sometimes used with a static resource, or to create a default, new, object to use as context. In most cases, there is already an existing database, a data source and, as mentioned, the DataContext is set to a ViewModel, possibly in the XAML, but frequently using a small piece of code-behind.

Each FrameworkElement has a DataContext Property, so these can be different. But why would there be two completely unrelated contexts used in the same Window? For example, what is the connection between your Employee and a Payroll class? It is a ViewModel that could provide a single context that is a hierarchical set based on both Employee and Payroll.

(I'm relying on tlhIn`toq to correct any misstatement ;) )
Was This Post Helpful? 1
  • +
  • -

#6 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Data binding in WPF from multiple classes

Posted 27 October 2015 - 01:28 PM

Can you? Yes. Should you? No.
If you're going to require a different DataContext then you probably want to make a new component/control. But don't do it for each StackPanel.

Going back to the example of a restaraunt order taking system:
If the GUI probably has:
  • A section for all the meals:
  • A section for the current ticket:
  • A section listing all the servers on duty
  • A section listing all the tickets for the current logged-in server


You wouldn't make this as one giant Window definition.
Instead you would make a control that just shows all the meals. Now that control is reusable.
You make a control that shows all the meals of the current ticket. Now that control is reusable.
You make a control that lists all the on-duty staff. Now that control is reusable.

Your Window now is just a simple set of controls. Probably less than 100 lines of XAML.
You can set the DataContext for each control and it makes sense:
The 'DutyStaffControl' has its DataContext set to the "DutyStaffCollection".
The 'MealsControl' has its DataContext set to the 'TodaysMealsCollection'.
and so on.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1