c# – 绑定WPF DataGrid文本列的前景

我尝试构建一个DataGrid,我想将其中一个TextColums的Foreground属性绑定到Date,如果Date是过去的话,它会变为红色.

这里是XAML:

<toolkit:DataGridTextColumn 
   Binding="{Binding Path=Prüfdatum, Converter={StaticResource TimestampToDateConverter}}"
   Header="Prüfdatum" 
   Foreground="{Binding Path=Prüfdatum, Converter={StaticResource TimestampToColorConverter},
   ConverterParameter=Prüfdatum}" />

这是我的转换器:

    class TimestampToColorConverter: IValueConverter
{
    #region IValueConverter Member

    public object Convert(object value, Type targetType, 
           object parameter, System.Globalization.CultureInfo culture)
    {
        string Datum = value.ToString();
        int year = System.Convert.ToInt32(Datum.Substring(6, 4));
        int month = System.Convert.ToInt32(Datum.Substring(3, 2));
        int day = System.Convert.ToInt32(Datum.Substring(0, 2));
        int hour = System.Convert.ToInt32(Datum.Substring(11, 2));
        int minute = System.Convert.ToInt32(Datum.Substring(14, 2));
        int second = System.Convert.ToInt32(Datum.Substring(17, 2));
        DateTime Time = new DateTime(year, month, day, hour, minute, second);
        if (Time < System.DateTime.Now)
        {
            return Brushes.Red as Brush;
        }
        else
        {
            return Brushes.Black as Brush;
        }

    }

    public object ConvertBack(object value, Type targetType, 
         object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }

    #endregion
}

我不知道出了什么问题,但转换器甚至没有出现问题(第一个转换器工作正常).输出窗口显示如下:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement
or FrameworkContentElement for
target element.
BindingExpression:Path=Prüfdatum;
DataItem=null; target element is
‘DataGridTextColumn’
(HashCode=16187528); target property
is ‘Foreground’ (type ‘Brush’)

伙计们,我希望你能帮助我

谢谢

解决方法:

由于您已绑定到DataGrid,因此不需要DataGridTextColumn中的“绑定”,也不需要ConverterParameter,因为您的转换器未使用该参数.试试以下

<toolkit:DataGridTextColumn  Header="Prüfdatum" Foreground="{Binding Path=Prüfdatum, Converter={StaticResource TimestampToColorConverter}}" />
上一篇:c# – WPF数据网格 – 如何隐藏可见的下一列/行?


下一篇:c# – 具有动态可编辑列的DataGrid