[英]How to change DataGrid row background color after row was edited
我有一个DataGrid
,用户可以在其中编辑一些列。 现在我想从编辑的行中更改背景颜色。
我使用RowEditEnding
事件。
但是现在当编辑一行时,更多的行不仅仅是那个被着色的行。
XAML:
<DataGrid x:Name="dgArtikel" ItemsSource="{Binding listViewItems}" AutoGenerateColumns="False" RowEditEnding="dgArtikel_RowEditEnding" CanUserAddRows="False">
代码背后:
private void dgArtikel_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
listViewItems itm = (listViewItems)dgArtikel.SelectedItem;
DataGridRow row = dgArtikel.ItemContainerGenerator.ContainerFromItem(itm) as DataGridRow;
row.Background = Brushes.YellowGreen;
}
我刚刚尝试过这样的场景,并且确实在那个事件上,行颜色发生了变化。 但是在下一次编辑时,新行的颜色也会改变。 所以我们现在有两行背景设置为YellowGreen。
一个建议是将行定义为全局变量。
private DataGridRow row;
private void dgArtikel_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
if (row != null)
row.Background = Brushes.White;
listViewItems itm = (listViewItems)dgArtikel.SelectedItem;
row = dgArtikel.ItemContainerGenerator.ContainerFromItem(itm) as DataGridRow;
row.Background = Brushes.YellowGreen;
}
这样,过去编辑的行将返回其初始颜色。 我不确定这是否正是你想要的。
您可以尝试在模型中添加已检查的标志:
private bool _IsChecked;
public bool IsChecked
{
get { return _IsChecked; }
set
{
_IsChecked = value;
PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
}
}
定义转换器:
public class BoolToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool val = (bool) value;
if (val)
return Brushes.GreenYellow;
else
{
return Brushes.White;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
并为DataGridRow添加样式:
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="{Binding IsChecked, Converter={StaticResource BoolToColorConverter}}"></Setter>
</Style>
在RowEditEnding中,您可以将IsChecked从模型设置为true,但后来我不知道您希望如何或在何处将其设置为false。 我不知道您的具体情况,但此信息可能会有所帮助。 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.