簡體   English   中英

在wpf中顯示繼承對象的最佳方法是什么?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM