gpt4 book ai didi

c# - 转换器获取 DataRowView 而不是 DataGridCell

转载 作者:行者123 更新时间:2023-12-04 02:08:47 24 4
gpt4 key购买 nike

DataGrid.ItemSource 在代码后面设置为 dataview。列名和计数需要即时更改,因此对象列表不能很好地工作。

我的表格显示完全正常。这很好,但是我的 GridCellStyle 将 DataRowView 传递给转换器,而不是我期望传递的 DataGridCell。

有没有办法获取 DataGridCell 内容指示当前传递给我的转换器的列的内容?

<UserControl x:Class="TestUI.SilveusTable"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestUI"
mc:Ignorable="d"
>
<UserControl.Resources>
<local:CbotValueConverter x:Key="CbotValueConverter" />
<Style x:Key="GridCellStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Yellow"/>
<Setter Property="Foreground" Value="{Binding Converter={StaticResource CbotValueConverter}}"/>
</Style>
</UserControl.Resources>
<Grid>
<DataGrid x:Name="DataGrid1" IsReadOnly="True" CellStyle="{StaticResource GridCellStyle}" />
</Grid>
</UserControl>

这是我的转换器类

  [ValueConversion(typeof(DataGridCell), typeof(SolidColorBrush))]
public class CbotValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var dgc = (DataGridCell) value;
var rowView = (DataRowView) dgc.DataContext;
var v = rowView.Row.ItemArray[dgc.Column.DisplayIndex];

decimal amount;
if (decimal.TryParse(v.ToString(), out amount))
{
if (amount >= 10) return Brushes.Red;
if (amount >= 5) return Brushes.Blue;
if (amount > 0) return Brushes.Green;
}

return Brushes.Black; //quantity should not be below 0
}

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

最佳答案

更改绑定(bind)的来源

使用当前绑定(bind)声明,DataGridCell 的 DataContext 是源

Value="{Binding Converter={StaticResource CbotValueConverter}}"

要使用 DataGridCell 本身,请添加 RelativeSource Self 部分(指您要设置绑定(bind)的元素)

Value="{Binding Converter={StaticResource CbotValueConverter}, 
RelativeSource={RelativeSource Self}}"

关于c# - 转换器获取 DataRowView 而不是 DataGridCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40868783/

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