[英]ContentControl is failing to bind to DataTemplate
I'm unable to bind the <ContentControl Content={Binding Type}/>
to the local resources <DataTemplate>
when binding my custom property on my POCO class called Type
(I'm hoping it's not down to the bad choice of naming).在我的名为
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 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>
The Type
property is (as you've probably guessed) a System.Type
and the output within my WPF application is always the output of ToString()
which I'm guessing is down to a failed match of my <DataTemplate>
. Type
属性是(正如您可能已经猜到的)一个System.Type
并且我的 WPF 应用程序中的输出始终是ToString()
的输出,我猜这归结为我的<DataTemplate>
的失败匹配。 If I change the ContentControl
to Content={Binding}
and set the <DataTemplate>
to accept the data type of the POCO class ReportItemModel
it works as intended.如果我将
ContentControl
更改为Content={Binding}
并将<DataTemplate>
设置为接受 POCO 类ReportItemModel
的数据类型,它会按预期工作。 The only difference I can see is that ReportItemModel
has been instantiated where as the Type
property has not.我能看到的唯一区别是
ReportItemModel
已被实例化,而Type
属性尚未实例化。
The issue was down to the XAML DataType="{x:Type moduleTypes:ReportModule}"
calling behind the scenes GetType()
on a System.Type
which would always return a System.RuntimeType
as the object was never instantiated and always (at that point) a System.Type
(a "Brain Fart" moment to say the least).问题归结为 XAML
DataType="{x:Type moduleTypes:ReportModule}"
在System.Type
上调用幕后GetType()
会始终返回System.RuntimeType
因为对象从未实例化并且始终(在那个点)一个System.Type
(至少可以说是“脑放屁”时刻)。 I was able to get around the issue by using a ValueConverter
on the binding <ContentControl Content={Binding Type}
and returning the BaseClass
name as a string
.通过在绑定
<ContentControl Content={Binding Type}
上使用ValueConverter
并将BaseClass
名称作为string
返回,我能够解决这个问题。 Using the BaseClass
name, It was easy enough to use a couple of DataTriggers
which changed the ContentTemplate
value to one of my matched custom DataTemplate
's using a similar method shown here .使用
BaseClass
名称,使用几个DataTriggers
很容易,这些DataTriggers
使用此处显示的类似方法将ContentTemplate
值更改为我匹配的自定义DataTemplate
值之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.