转换器获取 DataRowView 而不是 DataGridCell

Converter gets a DataRowView instead of DataGridCell

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

我的 table 显示完全正常。这很好,但是 我的 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>

这是我的转换器Class

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

更改绑定的来源

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

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

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

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