在我的项目中,我有一个Units
列表,它被用作DataGrid的数据源。 Units
类型有两种类型的子类AUnits
和BUnits
。列表中的每个Unit
都是AUnit
或BUnit
。我的问题是当我尝试绑定到特定于其中一个子类单元类型的属性时,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
的子类上的属性,因此XAML认为我正在尝试访问不存在的属性。
我已阅读this answer,到目前为止,我已尝试了以下某些语法:
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:
<DataGrid x:Name="JobListView"
AutoGenerateColumns="False"
ItemsSource="{Binding UnitStatusCollection, Mode=TwoWay}"
CanUserDeleteRows="False"
Style="{StaticResource JobGridViewStyle}"
SelectedItem="{Binding JobsListViewSelectedUnitInfo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Utility:DataGridColumnsBehavior.BindableColumns="{Binding DataGridColumns}"
ContextMenu="{StaticResource ListViewContextMenu}"
Margin="10,5,10,2"
Grid.Row="2"
SelectionMode="Single"
SelectionUnit="FullRow"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
RowStyle="{StaticResource DataGridRowStyle}"
CellStyle="{StaticResource DataGridCellStyle}"
AlternationCount="2"
HorizontalScrollBarVisibility="Visible"
VerticalScrollBarVisibility="Visible"
CanUserResizeRows="False"
HorizontalGridLinesBrush="#d6d6d6"
VerticalGridLinesBrush="#d6d6d6"
Background="#EAEAEA"
>
ItemsSource
设置为UnitStatusCollection
,这是ObservableCollection
类UnitInfo
,其中包含Unit
和UnitStatus
。我需要访问MaxDepthRelativeToEntry
Unit
中的UnitInfo
媒体资源。但我需要能够将Unit
视为AUnit
答案 0 :(得分:2)
如果您绑定到Unit
个对象列表,那么DataContext
的{{1}}应该是DataGridTextColumn
或AUnit
个对象本身,所以您的绑定路径应该只是BUnit
。
对于仅存在于一个SubClass但不存在于其他SubClass上的属性,您可能会收到某种运行时警告,但它不应该抛出异常。
这是一个快速代码示例,以举例说明:
XAML:
new Binding("MaxDepthRelativeToEntry")
Code-Behind:
<DataGrid x:Name="dgTest" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="A" Binding="{Binding A}" />
<DataGridTextColumn Header="B" Binding="{Binding B}" />
<DataGridTextColumn Header="C" Binding="{Binding C}" />
</DataGrid.Columns>
</DataGrid>
其中类定义为
var test = new List<ClassA>();
test.Add(new ClassB() { A = "A", B = "B" });
test.Add(new ClassC() { A = "A", C = "C" });
dgTest.ItemsSource = test;
输出:
如果我在代码隐藏中而不是在XAML中编写绑定,它的工作方式也完全相同:
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; }
}