[英]What is the best way to show an inherited object in wpf?
可以说我有这个:
public class Result
{
public bool Success { get; set; }
public string Description { get; set; }
}
然后,我想添加另一个级别,如下所示:
public class AssertionFailedResult : Result
{
public string Expected { get; set; }
public string Actual { get; set; }
}
在WPF中,我将如何以一种方式显示简单结果,而以另一种方式显示断言失败的结果? 我想基本上根据类型制作一个模板。
如果您在资源字典中创建DataTemplate并设置DataType属性,但未设置x:Key属性,则框架将根据对象的运行时类型将DataTemplate与对象相关联。 不论好坏,继承都没有作用。 换句话说,即使你没有一个模板,其中的数据类型是“AssertionFailedResult”,该框架将不绑定类型“AssertionFailedResult”的对象模板在数据类型是“结果”。
编辑:对不起,我倒退了。 DataTemplates 确实具有“多态”行为。 样式没有。 无论如何,框架都应使用更具体的DataType绑定到DataTemplate。
我接受了丹尼尔的回答,并举例说明了这一点。 我认为发布代码可能会有所帮助:
<Window x:Class="SampleWpfApplication.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:SampleWpfApplication="clr-namespace:SampleWpfApplication">
<Window.Resources>
<DataTemplate DataType="{x:Type SampleWpfApplication:Result}">
<Label>Simple Result</Label>
</DataTemplate>
<DataTemplate DataType="{x:Type SampleWpfApplication:AssertionFailedResult}">
<Label>Assertion Failed!</Label>
</DataTemplate>
</Window.Resources>
<ContentControl x:Name="contentControl" Content="{Binding Path=Result}" />
</Window>
接下来,一个模型类,它是窗口的数据上下文:
public class Model
{
public Result Result { get; set; }
}
在MainWindow中,我将DataContext设置如下:
DataContext = new Model()
{
Result = new AssertionFailedResult()
{
Success = false,
Description = "Assertion failed",
Expected = "1",
Actual = "1"
}
};
因此,有了DataTemplate,wpf知道了如何呈现控件而不需要任何其他指导。 再次感谢,丹尼尔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.