所以我之前的问题似乎无法回答,所以我将根据自己的建议尝试一下。
我正在寻找的功能是,当单元格中的数据被编辑时,让数据网格更改单元格的前景(甚至背景)。
我的模型看起来像这样:
Public class Shipment : PropertyChangedBase
{
#region Fields
private ShippingService.Shipment.lbnshipment _localShipment;
private ShippingService.Shipment.lbnshipment _originalShipment;
#endregion
#region Properties
public int ShipmentID
{
get { return _localShipment.ShipmentID; }
set
{
if(value != _localShipment.ShipmentID)
{
_localShipment.ShipmentID = value;
NotifyOfPropertyChange(() => ShipmentID);
}
}
}
public Shipment(ShippingServices.Shipment.lbnShipment localshipment)
{
_originalShipment = localshipment;
_localShipment = localshipment;
}
//This Section is my best guess solution, but it just a guess
public Color HasChanged(string Property)
{
switch(Property)
{
case "ShipmentID":
if(_localShipment.ShipmentID != _originalShipment.ShipmentID)
{
return Colors.Red;
} else {
return Colors.Black;
}
break;
}
}
}
我显然已经删除了大部分属性,现在的 HasChanged 纯粹是神话,但我希望以某种方式,我可以将 DataGridTextColumn 前景(或希望背景)绑定到此 HasChanged 方法,并且以某种方式传递当前正在调用该方法的参数。
<DataGridTextColumn Header="ShipmentID" Binding="{Binding ShipmentID}" Foreground="{Binding HasChanged}" />
我希望有一些聪明的方法可以让绑定识别哪个属性已更改,就像 IDataErrorInfo 允许为每个属性绑定验证一样。虽然我不知道它在后台实际上是如何运作的。
它需要一个转换器,不是吗?所以你的绑定看起来像这样:
<DataGridTextColumn.Foreground>
<SolidColorBrush Color="{Binding Converter={StaticResource hasChangedConverter}, ConverterParameter='ShipmentID'}"/>
</DataGridTextColumn.Foreground>
你的转换器看起来像(剥离无关代码):
class HasChangedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var shipment = value as Shipment;
var property = parameter as string;
return shipment.HasChanged(property);
}
}
更新: 如上所示在转换器参数上使用单引号应该可行。如果失败,您可以使用扩展格式进行绑定:
<SolidColorBrush.Color>
<Binding Converter="{StaticResource hasChangedConverter}" ConverterParameter="ShipmentID"/>
</SolidColorBrush.Color>
更新二: ...显然我们不能随意更改
DataGridTextColumn
的背景,因此将列的 XAML 更改为如下所示:
<DataGridTemplateColumn Header="ShipmentID">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ShipmentID}">
<TextBlock.Background>
<SolidColorBrush Color="{Binding Path=ShipmentID, Converter={StaticResource HasChangedConv}}"/>
</TextBlock.Background>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
有两种选择:
如果这个
Property
东西在 UI 中绑定到 ViewModel 您可以监听 ViewModel
中该属性的更改,然后相应地更改颜色。如果没有,请使用命令系统。理想的场景是:
- UI 向
Command
发送 ViewModel
表示某些内容已发生变化。 ViewModel
执行命令,并更改 Color
字段。需要通知 UI 颜色已更改。这是 ICommand 接口的实现: