如何在XAML中转换以访问子类属性

在我的项目中,我有一个Units列表,它被用作DataGrid的数据源。 Units类型有两种类型的子类, AUnitsBUnits 。 列表中的每个Unit都是AUnitBUnit 。 我的问题是当我尝试绑定到特定于其中一个子类单元类型的属性时,XAML没有看到它,我只是回到0。 通常情况下,如果这是在C#中完成的,我会抛出它并访问该属性,但我在代码中无法做到这一点。 绑定是在C#中创建的,如下所示:

  dgtc.Header = Properties.Resources.MaxPressure; dgtc.MinWidth = 25; dgtc.Width = Properties.Settings.Default.MaxPressureColumnWidth; dgtc.IsReadOnly = true; dgtc.Binding = new Binding("Unit.MaxDepthRelativeToEntry") { Converter = new DistanceUnitsConverter() }; 

其中dgtc是DataGridTextColumn。 Unit.MaxDepthRelativeToEntry为0,因为它是AUnit的子类上的AUnit ,因此XAML认为我正在尝试访问不存在的属性。

我已经阅读了这个答案 ,到目前为止我已经尝试了以下一些语法:

 dgtc.Binding = new Binding("AUnit.MaxDepthRelativeToEntry") dgtc.Binding = new Binding("Unit(MyNameSpace:AUnit).MaxDepthRelativeToEntry") dgtc.Binding = new Binding("Unit(MyNameSpace:AUnit.MaxDepthRelativeToEntry)") 

并且无法让任何人工作。 我也试过通过转换器这样做,但问题是,当我构建DataGrid /设置绑定/等时,我没有可用的单元列表。 所以我无法从实例中获取属性并将其返回。 有没有人知道我能以任何方式,最好是在XAML中,获取我绑定类型的子类类型的属性?

编辑:

我的DataGrid具有以下XAML:

  

ItemsSource设置为UnitStatusCollection ,它是一个名为UnitInfo的类的ObservableCollection ,它包含一个Unit和一个UnitStatus 。 我需要在MaxDepthRelativeToEntryUnit中访问属性UnitInfo 。 但我需要能够将Unit视为AUnit

如果绑定到Unit对象列表,则DataGridTextColumnDataContext应该是AUnitBUnit对象本身,因此绑定路径应该是new Binding("MaxDepthRelativeToEntry")

对于仅存在于一个SubClass而不存在于其他SubClass上的属性,您可能会获得某种运行时警告,但它不应抛出exception。

这是一个快速代码示例,以举例说明:

XAML:

        

代码隐藏:

 var test = new List(); test.Add(new ClassB() { A = "A", B = "B" }); test.Add(new ClassC() { A = "A", C = "C" }); dgTest.ItemsSource = test; 

将类定义为

 public class ClassA { public string A { get; set; } } public class ClassB : ClassA { public string B { get; set; } } public class ClassC : ClassA { public string C { get; set; } } 

输出:

在此处输入图像描述

如果我在代码隐藏而不是在XAML中编写绑定,它的工作方式也完全相同:

 colB.Binding = new Binding("B")