目前我绑定了一个List<T>
,所以我必须为每一列分别做特定的设置,并创建单独的DataTemplate
就像这样:
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock TextAlignment="Center"
Text="{Binding ObColl[1].Std, UpdateSourceTrigger=PropertyChanged}"
Background="{Binding ObColl[1].DienstColor, TargetNullValue=Transparent,FallbackValue=Transparent}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
但我希望将DataTemplate
作为资源创建一次
<DataGrid.Resources>
<DataTemplate x:Name="MyCellTemplate">
<TextBlock TextAlignment="Center"
Text="{Binding Std, UpdateSourceTrigger=PropertyChanged}"
Background="{Binding DienstColor, TargetNullValue=Transparent,FallbackValue=Transparent}" />
</DataTemplate>
</DataGrid.Resources>
并像这样使用它
<DataGridTemplateColumn CellTemplate="{StaticResource MyCellTemplate} ??{Binding ObColl[1]}??"/>
但是为了这样做,我需要在我的DataGridTemplateColumn
中指定DataContext
(ObColl[Idx]),但我该怎么做呢?
编辑
XAML应该像这样:
<DataGrid Name="dataGrid1"
ItemsSource="{Binding Itemlist, UpdateSourceTrigger=PropertyChanged}">
<DataGrid.Resources>
<DataTemplate x:Key="MyCellTemplate">
<TextBlock TextAlignment="Center"
Text="{Binding Std, UpdateSourceTrigger=PropertyChanged}"
Background="{Binding DienstColor, TargetNullValue=Transparent, FallbackValue=Transparent}" />
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<!-- Column 1 -->
<DataGridTemplateColumn CellTemplate="{StaticResource MyCellTemplate}"
DataContext={Binding ObColl[0]}/>
<!-- Column Header 2 -->
<DataGridTemplateColumn CellTemplate="{StaticResource MyCellTemplate}"
DataContext={Binding ObColl[1]}/>
</DataGrid.Columns>
</DataGrid>
DataContext={Binding ObColl[1]}
是问题所在,因为它并不存在……
DataGridTemplateColumn
的DataContext
?这已经被DataGrid
控件隐式完成了,不是吗?在DataTemplate
中,您应该已经可以访问绑定到DataGrid.ItemsSource
属性的集合中对象的属性。 - Sheridan[0]
(获取第一个)。但如果我使用DataTemplate作为StaticResource,我需要指定DataContext... - WiiMaxxList<T>
没有被设置为DataGrid.ItemsSource
属性吗?如果我使用一个作为 StaticResource 的 DataTemplate,我需要指定 DataContext - 我不认为这是正确的。在这种情况下,唯一需要指定 DataContext 的时候是,如果你想要绑定到与数据绑定到 DataGrid.ItemsSource 属性的集合中的不同对象...那么这就是你想要做的事情吗? - SheridanDataGrid.ItemsSource
是一个包含两个属性的List<MyRow>
,第一个属性是MyRowheader
,第二个属性是MyCellList
,它是一个List<T>
。 - WiiMaxxDataGrid
的每一行中显示MyCellList
中的一个值吗?如果是这样,那么这个值是相同的还是每一行都展示来自MyCellList
不同的值? - Sheridan