【发布时间】:2013-12-04 07:56:07
【问题描述】:
目前我绑定到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属性。 -
我的 DataContext 是一个访问对象的列表,我需要指定列表中的项目,例如
[0](获取第一个),但如果我使用 DataTemplate作为 StaticResource 我需要指定 DataContext ... -
这个
List<T>不是设置为DataGrid.ItemsSource属性吗? 如果我使用 DataTemplate 作为 StaticResource,我需要指定 DataContext - 我认为这不是真的。唯一需要指定DataContext的时间(在这种情况下)是,如果您想将Bind指向与集合中数据绑定到DataGrid.ItemsSource属性的对象不同的对象... 那你想做什么? -
不,更复杂的是我的
DataGrid.ItemsSource是一个 List,其中包含 2 个属性,第一个是 MyRowheader,第二个是MyCellList,这是一个List<T>跨度> -
您只想在
DataGrid的每一行中显示来自MyCellList的一个值?如果正确,它是 same 值,还是每行与MyCellList不同的值?
标签: wpf binding datagrid datatemplate celltemplate