Contentpresenter with type based datatemplate selection and binding

拈花ヽ惹草 提交于 2019-12-04 10:51:11
Sheridan

I think you'll benefit from reading about DataTemplates. First, I'd advise you to have a good, long read of the Data Templating Overview page on MSDN. As I mentioned in my comments, you should not use a ContentPresenter in your DataTemplates. From the linked page:

You typically use the ContentPresenter in the ControlTemplate of a ContentControl to specify where the content is to be added.

The thing that you seem to be missing is how and what to data bind to from inside a DataTemplate. The DataContext of the DataTemplate will automatically be set to an instance of the type specified in the DataType property. Therefore, the properties that the DataTemplate has access to will also depend on the type specified in the DataType property. For example, you cannot do this, because a string does not have a Value property.

<DataTemplate DataType="{x:Type System:String}">
    <TextBox Text="{Binding Value}" BorderThickness="0" />
</DataTemplate>

Instead, for a string, you'd need to data bind to the whole DataContext value like this:

<DataTemplate DataType="{x:Type System:String}">
    <TextBox Text="{Binding}" BorderThickness="0" />
</DataTemplate>

Alternatively, if you had a class names SomeClass and that class has a Value property, then you could do this:

<DataTemplate DataType="{x:Type YourDataTypesPrefix:SomeClass}">
    <TextBox Text="{Binding Value}" BorderThickness="0"/>
</DataTemplate>

Now, because these DataTemplates have been defined without setting their x:Key values, the Framework will automatically render the content of each DataTemplate whenever it sees an object of the relevant type (and no other, explicit templates set). So try this out and if you still have a problem, let me know.

Martijn

I found sort of a workaround for this problem. The reason the binding did not work is because I bound to the content of the ContentControl. Two-way binding to a binding source does not work as stated here. This is the reason I got the exception. I still use the ContentControl with the DataTemplates to differentiate between the data types. But instead of binding to the content of the ContentControl I bind to the value the ContentControl binds to. Notice the Path in the binding.

<ContentControl Content="{Binding Value}" Grid.Column="2">
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type System:String}">
            <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=DataContext.Value}" BorderThickness="0" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type System:Int32}">
            <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=DataContext.Value}"
                     TextAlignment="Right"
                     BorderThickness="0"/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type System:Double}">
            <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=DataContext.Value}"
                     TextAlignment="Right"
                     BorderThickness="0"/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type System:Boolean}">
            <CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=DataContext.Value}"
                          HorizontalAlignment="Center"/>
        </DataTemplate>
    </ContentControl.Resources>
</ContentControl>

It is a solution to the problem. I just feel a bit uncomfortable for using the ContentControl just to diferentiate between the DataTypes and having an illogical binding.

Also, thank you for helping me unravel this problem Sheridan.

Already being uncomfortable with my solution I also ran into the problem of not being able to add a List DataType to the DataTemplates. I ended up using a DataTemplateSelector which resulted in much nicer code. Here it is:

The ContentControl. A container for the data which the DataTemplate is applied over:

<ContentControl Grid.Column="2" Content="{Binding}"
                ContentTemplateSelector="{StaticResource propertyItemTemplateSelector}">
</ContentControl>

A few DataTemplates and a declaration for the DataTemplateSelector:

<Style.Resources>
    <local:PropertyTemplateSelector x:Key="propertyItemTemplateSelector"/>
    <DataTemplate x:Key="dtStringValue">
        <TextBox Text="{Binding Path=Value}"
                 BorderThickness="0"
                 IsReadOnly="{Binding Path=IsReadOnly}">
        </TextBox>
    </DataTemplate>

    <DataTemplate x:Key="dtIntegerValue">
        <TextBox Text="{Binding Path=Value}"
                 TextAlignment="Right"
                 BorderThickness="0"
                 IsReadOnly="{Binding Path=IsReadOnly}"/>
    </DataTemplate>
...

The code for the DataTemplateSelector:

 public class PropertyTemplateSelector : DataTemplateSelector
 {
    public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
    {
        DataTemplate template = null;

        IPropertyItem propertyItem = item as IPropertyItem;

        if (propertyItem != null)
        {
            FrameworkElement element = container as FrameworkElement;
            if (element != null)
            {
                var value = propertyItem.Value;

                if (value is String)
                {
                    template = element.FindResource("dtStringValue") as DataTemplate;
                }
                else if (value is Int32)
                {
                    template = element.FindResource("dtIntegerValue") as DataTemplate;
                }
                 ....
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!