[英]What is the best way to show an inherited object in wpf?
Lets say I have this: 可以说我有这个:
public class Result
{
public bool Success { get; set; }
public string Description { get; set; }
}
Then I want to add another level, like this: 然后,我想添加另一个级别,如下所示:
public class AssertionFailedResult : Result
{
public string Expected { get; set; }
public string Actual { get; set; }
}
In WPF, how would I show the simple result one way and the assertion failed result another way? 在WPF中,我将如何以一种方式显示简单结果,而以另一种方式显示断言失败的结果? I'd like to basically make a template based on type.
我想基本上根据类型制作一个模板。
If you create a DataTemplate in a resource dictionary and set the DataType property, but don't set the x:Key property, the framework will associate the DataTemplate to objects based on the object's runtime type. 如果您在资源字典中创建DataTemplate并设置DataType属性,但未设置x:Key属性,则框架将根据对象的运行时类型将DataTemplate与对象相关联。 For better or worse, inheritance has no effect.
不论好坏,继承都没有作用。 In other words, even if you didn't have a template where the DataType was "AssertionFailedResult", the framework would not bind objects of type "AssertionFailedResult" to a template where the DataType was "Result".
换句话说,即使你没有一个模板,其中的数据类型是“AssertionFailedResult”,该框架将不绑定类型“AssertionFailedResult”的对象模板在数据类型是“结果”。
EDIT: Sorry, I got it backwards. 编辑:对不起,我倒退了。 DataTemplates do have a "polymorphic" behavior.
DataTemplates 确实具有“多态”行为。 Styles do not.
样式没有。 In any case, the frameworks should bind to the DataTemplate with the more specific DataType.
无论如何,框架都应使用更具体的DataType绑定到DataTemplate。
I took Daniel's answer and made an example out of it. 我接受了丹尼尔的回答,并举例说明了这一点。 I thought posting the code might be helpful:
我认为发布代码可能会有所帮助:
<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>
Next, a model class that is the data context of the window: 接下来,一个模型类,它是窗口的数据上下文:
public class Model
{
public Result Result { get; set; }
}
And in the MainWindow, I set the DataContext as follows: 在MainWindow中,我将DataContext设置如下:
DataContext = new Model()
{
Result = new AssertionFailedResult()
{
Success = false,
Description = "Assertion failed",
Expected = "1",
Actual = "1"
}
};
So with the DataTemplate, wpf knows how to render the control without any additional direction on my part. 因此,有了DataTemplate,wpf知道了如何呈现控件而不需要任何其他指导。 Thanks again, Daniel.
再次感谢,丹尼尔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.