Linking properties using DataTemplates and ContentControl

I liked this answer and it almost matched me.

But how can I achieve this if my DataTemplate is in an external ResourceDictionary ?

I use Prism, and I provide DataTemplates (for general CRUD views) by each module using these files:

 <ResourceDictionary ... some hidden ns here ... > <DataTemplate DataType="{x:Type model:Operation}"> <vw:OperationView /> </DataTemplate> <DataTemplate DataType="{x:Type model:Customer}"> <vw:CustomerView /> </DataTemplate> </ResourceDictionary> 

Then I use this answer to combine ResourceDictionaries into a Shell application, and I have a default CRUD view that has this code:

 <ContentControl Content="{Binding MyGenericObject}" /> 

In order for ContentControl automatically display the correct view. It works fine, but I want to know to bind the property of objects in each view.

What is an example of these views (OperationView.xaml):

 <UserControl x:Class="TryERP2.Cadastro.View.OperationView" ... some hidden NS ... > <StackPanel> <Label Content="Id" /> <TextBox Text="{Binding ????WHAT????}" /> <Label Content="Description" /> <TextBox Text="{Binding ????WHAT????}" /> </StackPanel> </UserControl> 

How can I bind these properties?

0
source share
2 answers

Since the DataContext behind the OperationView will be an object of type Operation , then you just bind to any property on Operation that you want

 <!-- DataContext will be model:Operation per your DataTemplate --> <UserControl x:Class="TryERP2.Cadastro.View.OperationView" ... some hidden NS ... > <StackPanel> <Label Content="Id" /> <TextBox Text="{Binding Id}" /> <Label Content="Description" /> <TextBox Text="{Binding Description}" /> </StackPanel> </UserControl> 
+2
source

DataContext in UserControl is your model object, so you can directly bind to its properties as follows:

 Text="{Binding SomeProperty}" 

(If only the path is specified, the binding refers to the DataContext , note that the answer you linked had the intention of having TwoWay binding on the DataContext itself, which was a primitive string, this cannot be done using a simple binding such as {Binding .} , you must specify the path to target the actual property)

+1
source

Source: https://habr.com/ru/post/912678/


All Articles