我尝试将我的代码更改为正确的绑定,但我有一些困难的例子。
当双击行的Id(第1列)存在于其他List(DataGrid)中时,我尝试着色为黄色,如下所示:
现在我在代码背后做的很简单:
private void ColorRow(int idIn)
{
foreach (RecordTransactionModel item in SelectedMonthDataGrid.ItemsSource)
{
if (item.Id == idIn)
{
var row = SelectedMonthDataGrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
row.Background = Brushes.Yellow;
return;
}
}
}
我现在在xaml中获得的最好成绩是:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger>
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource CultureConverter}">
<Binding Path="SelectedItem.Id" />
<Binding Path="RecordDetails" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="Yellow" />
</DataTrigger>
</Style.Triggers>
</Style>
和转换器:
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
// if both values are not zero ( are both binded )
if (values[0] != DependencyProperty.UnsetValue && values[1] != DependencyProperty.UnsetValue)
{
List<RecordDetailsModel> list = values[1] as List<RecordDetailsModel>;
int id = System.Convert.ToInt32(values[0]);
return list.Exists(x => x.IdIn == id);
}
return Binding.DoNothing;
}
并且它不起作用。如何使它工作?
编辑: 现在我想出了可行的解决方法,但我不认为它仍然是正确的解决方案: 我刚刚在1st Datagrid的模型中定义了第二个Datagrid的对象列表,并在每次更改时刷新它以指示id是否在列表中:
public List<RecordDetailsModel> RecordDetailsList { get; set; }
public bool IsSelected
{
get
{
if (RecordDetailsList == null)
return false;
return RecordDetailsList.Exists(x => x.IdIn == Id);
}
}
和xaml:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected,UpdateSourceTrigger=PropertyChanged}" Value="true">
<Setter Property="Background" Value="Yellow" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>