gpt4 book ai didi

silverlight - 使用 M-V-VM Light 根据 Silverlight 4 中的业务规则标准标记 DataGrid 行

转载 作者:行者123 更新时间:2023-12-03 10:50:20 26 4
gpt4 key购买 nike

如果包含该单元格的行符合给定规则(假设其文本必须具有值“不完整”),我编写了代码来更改 DataGrid 单元格的前景属性。我可以通过在后面的代码中捕获 LoadingRow 事件并在那里编写我的逻辑来使这项工作变得相当容易,但我觉得这不是一个非常优雅的 MVVM 实现。这是代码:

// Sets the foreground color of th 5th cell to red if the text in the cell corresponds 
// to a value specified in the ViewModel.
private void dgProfile_LoadingRow(object sender, DataGridRowEventArgs e)
{

this.dgProfile.SelectedIndex = e.Row.GetIndex();
DataGridColumn column = this.dgProfile.Columns[4];
FrameworkElement fe = column.GetCellContent(e.Row);
FrameworkElement result = GetParent(fe, typeof(DataGridCell));
if (result != null)
{
DataGridCell cell = (DataGridCell)result;
if (((TextBlock)cell.Content).Text == (this.DataContext as ProfileViewModel).strIncompleteActivityStatus) cell.Foreground = new SolidColorBrush(Colors.Red);
else cell.Foreground = new SolidColorBrush(Colors.Black);
}

}
private FrameworkElement GetParent(FrameworkElement child, Type targetType)
{
object parent = child.Parent;
if (parent != null)
{
if (parent.GetType() == targetType)
{
return (FrameworkElement)parent;
}
else
{
return GetParent((FrameworkElement)parent, targetType);
}
}
return null;
}

有人可以告诉我是否有更好的方法来使用 MVVM Light 工具包来实现这一点,也许是通过 RelayCommand 和一些聪明的数据绑定(bind)?

在此先感谢您的帮助!

最佳答案

您可以定义模板列并将前景属性绑定(bind)到返回适当 SolidColorBrush 的值转换器。

例如:

<data:DataGrid.Columns>
<data:DataGridTemplateColumn>
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyProperty}"
Foreground="{Binding MyProperty, Converter={StaticResource MyConverter}}"/>

</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
</data:DataGrid.Columns>

和转换器:
public class MyConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
string propertyValue = (string)value;

if (propertyValue == strIncompleteActivityStatus)
return new SolidColorBrush(Colors.Red);
else
return new SolidColorBrush(Colors.Black);
}
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

更多细节在这里:

DataGrid cell color based on cell value

关于silverlight - 使用 M-V-VM Light 根据 Silverlight 4 中的业务规则标准标记 DataGrid 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5863086/

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