WPF Binding: Binding to Parent DataContext

OK. This is WPF and I am trying to link my window to my ViewModel. The VM looks like this:

public class VM
{
    public SalesRecord SR {get; set;} 
    public List<string> AllSalesTypes {get; set;}
}

public class SalesRecord
{
    public int ID {get; set;} 
    public DateTime Date {get; set;}
}

      

Here's my XAML:

...
<TextBox Text="{Binding Path=ID, Mode=TwoWay}"  />
<TextBox Text="{Binding Path=Date, Mode=TwoWay}"  />
<ComboBox ItemsSource="{Binding AllSalesTypes}" Text="{Binding Path=SalesType, Mode=TwoWay}" />
...

      

I am setting a data context for an object VM

at runtime like this:

this.DataContext = _vm.SR;

      

Now binding expressions work for all mine TextBoxes

that point to object properties SR

(for example, ID

and Date

), but ComboBox

that should display a list of all SalesTypes doesn't work, obviously because it AllSalesTypes

is a member of the class VM

.

My questions are: is there a way to write an anchor expression that looks like the parent of the current one DataContext

?

+3


source to share


2 answers


I don't know how you can use Binding to get the parent of the DataContext.
Just like if you have a class A

that has a property named MyProperty

and you write:

 object o = MyAInstance.MyProperty;

      

You have no way to find MyAInstance

from your instance o

.

Your options are either used:, this.DataContext = _vm

and the following properties are available:



 <TextBox Text="{Binding SR.ID}" />

      

OR add a property Parent

to SalesRecord

and manually configure it to point to the VM, then something like this will work:

 <TextBox Text="{Binding ID}" />
 <ComboBox ItemsSource="{Binding Parent.AllSalesTypes}" />

      

+2


source


You'd better make a model (data context) to view the view model (hence the name) and change the textbox bindings to:

<TextBox Text="{Binding SR.ID}" />
<TextBox Text="{Binding SR.Date}" />

      



I also highly recommend using the MVVM framework if you are using MVVM. You should really be embedding INotifyPropertyChanged

view models in your types - the MVVM framework provides an implementation of this.

0


source







All Articles