【发布时间】:2017-03-18 14:55:33
【问题描述】:
我有一个数据网格,它的一列中有一个嵌套的数据网格。我需要从子datagid中的行数触发主datagrid行背景颜色。
这是一个简化的例子。
XAML
<Grid>
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding rigList}" AutoGenerateColumns="False" CanUserAddRows="false">
<DataGrid.Resources>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Items.Count, ElementName=dataGridInner}" Value="2">
<Setter Property="Background" Value="LightBlue"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Items.Count, ElementName=dataGridInner}" Value="1">
<Setter Property="Background" Value="LightGreen"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Description" Binding="{Binding Description}" Width="*"/>
<DataGridTemplateColumn Header="Item/Price" Width="220">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<DataGrid x:Name="dataGridInner" ItemsSource="{Binding Items}" HeadersVisibility="None" AutoGenerateColumns="False" CanUserAddRows="false" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn Binding="{Binding Price}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
C#
public class Item
{
public string Name { get; set; }
public int Price { get; set; }
}
public class DataTable
{
public List<Item> Items { get; set; }
public string Description { get; set; }
}
public partial class MainWindow : Window
{
public ObservableCollection<DataTable> itemList { get; set; }
public MainWindow()
{
InitializeComponent();
itemList = new ObservableCollection<DataTable>
{
new DataTable() {
Items = new List<Item> {
new Item { Name = "Phone", Price = 220 },
new Item { Name = "Tablet", Price = 350 },
},
Description = "Electronic gadgets" },
new DataTable() {
Items = new List<Item> {
new Item { Name = "Teddy Bear", Price = 2200 },
},
Description = "Exclusive teddy bear" }
};
dataGrid1.ItemsSource = itemList;
}
}
Here's the picture of the table this code yields.
因此,通过将触发器放入数据网格的资源中,我至少可以使用 ElementName 访问子数据网格模板。但是 setter 显然只在孩子的范围内应用 Background 属性。我需要的是,如果子数据网格有两行,则整个父行将是蓝色的。
如何实现?
【问题讨论】:
-
我认为你不需要
, ElementName=dataGridInner绑定的一部分。Items是行 DataContext 的属性。而不是将样式放在<DataGrid.Resources>中为dataGrid1 设置<DataGrid.RowStyle>
标签: wpf templates binding triggers nested