Binding properties through DataTemplates and ContentControl

故事扮演 提交于 2019-12-29 08:26:06

问题


I liked this answer, and it almost fit me.

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

I'm using Prism and I provide the DataTemplates (for generic CRUD views) by each module, by using files like this:

<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 merge the ResourceDictionaries into the Shell app and I have a default CRUD view which has that code:

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

That ContentControl automatically pull the correct view. It's working fine, but I want to know bind the property of the objects in each view.

That's a sample 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?


回答1:


Since the DataContext behind OperationView will be an object of type Operation, then you simply bind to whatever property on Operation 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:


The DataContext in the UserControl is your model object, so you can directly bind to its properties like this:

Text="{Binding SomeProperty}"

(If only a path is specified the binding is relative to the DataContext, note that in the answer you linked the intention was to have a TwoWay binding on the DataContext itself which was a primitive string, this cannot be done using a simple binding like {Binding .}, a property path targeting an actual property needs to be specified)



来源:https://stackoverflow.com/questions/8987709/binding-properties-through-datatemplates-and-contentcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!