【问题标题】:ContentControl is failing to bind to DataTemplateContentControl 无法绑定到 DataTemplate
【发布时间】:2018-03-10 23:14:42
【问题描述】:

在我的名为 Type 的 POCO 类上绑定我的自定义属性时,我无法将 <ContentControl Content={Binding Type}/> 绑定到本地资源 <DataTemplate>(我希望这不是因为命名的错误选择)。

ReportItemModel

public class ReportItemModel
{
        public ReportItemModel(string name, ReportItemType itemType, Type type)
        {
            Name = name;
            ItemType = itemType;
            Type = type;
        }

        public string Name { get; }
        public ReportItemType ItemType  { get; }
        public Type Type { get; }
}

XAML

<ContentControl Content="{Binding Type}"  Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3">

      <ContentControl.Resources>
            <DataTemplate DataType="{x:Type moduleTypes:ReportModule}">
                   <Label>Test</Label>
             </DataTemplate>
      </ContentControl.Resources>

</ContentControl>

Type 属性是(您可能已经猜到了)System.Type,而我的 WPF 应用程序中的输出始终是 ToString() 的输出,我猜这是因为我的 @ 匹配失败987654329@。如果我将ContentControl 更改为Content={Binding} 并将&lt;DataTemplate&gt; 设置为接受POCO 类ReportItemModel 的数据类型,它将按预期工作。我能看到的唯一区别是 ReportItemModel 已经实例化,而 Type 属性没有。

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    问题归结为 XAML DataType="{x:Type moduleTypes:ReportModule}"System.Type 的幕后调用 GetType(),这将始终返回 System.RuntimeType,因为该对象从未实例化并且始终(在那时)System.Type (至少可以说是一个“脑放屁” 时刻)。我能够通过在绑定&lt;ContentControl Content={Binding Type} 上使用ValueConverter 并将BaseClass 名称作为string 返回来解决这个问题。使用BaseClass 名称,很容易使用一对DataTriggersContentTemplate 值更改为我匹配的自定义DataTemplate 之一,使用类似的方法显示here

    【讨论】:

      猜你喜欢
      • 2014-11-04
      • 2016-03-17
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多