gpt4 book ai didi

c# - WPF MVVM 带参数的数据绑定(bind)?

转载 作者:太空宇宙 更新时间:2023-11-03 20:08:04 26 4
gpt4 key购买 nike

所以我之前的问题似乎无法回答,所以我将根据自己的建议尝试一下。

我正在寻找的功能是,当单元格中的数据已被编辑时,让数据网格更改该单元格的前景(甚至背景)。

我的模型看起来像这样:

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 前景(或希望背景)绑定(bind)到此 HasChanged 方法,并以某种方式传递当前正在调用该方法的参数。

<DataGridTextColumn Header="ShipmentID" Binding="{Binding ShipmentID}" Foreground="{Binding HasChanged}" />

我希望有一些聪明的方法可以让绑定(bind)识别哪个属性发生了变化,这与 IDataErrorInfo 允许对每个属性绑定(bind)验证的方式非常相似。虽然我不知道它在后台实际如何运作。

最佳答案

它需要一个转换器,不是吗?所以你的绑定(bind)看起来像这样:

<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);
}
}

更新:如上所示在转换器参数上使用单引号应该有效。如果做不到这一点,您可以使用扩展格式进行绑定(bind):

<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>

关于c# - WPF MVVM 带参数的数据绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21777164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com