我有一个wpf数据网格,在datatemplate中有一个标签。我想将文本的颜色绑定到属性,但它不起作用。
这是xaml。
<DataGrid x:Name="ResultsDataGrid" CanUserSortColumns="True" MouseDown="ResultsDataGrid_OnMouseDown" SelectionChanged="ResultsDataGrid_OnSelectionChanged"
IsReadOnly="False" AlternatingRowBackground="WhiteSmoke" CanUserAddRows="False" Margin="10" AutoGenerateColumns="False" VerticalAlignment="Stretch">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Test ID" Width="150" IsReadOnly="True" SortMemberPath="TestDate">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label Foreground="{Binding PassedColor}" Content="{Binding TestID}"></Label>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
这是属性。
public Brush PassedColor
{
get
{
return new SolidBrush(Color.Red);
}
}
我似乎无法弄清楚我做错了什么。
如果删除绑定并将前景设置为red
则可行。所以它绝对是绑定的东西。
编辑:
这是整个对象
public class LabelInfo : INotifyPropertyChanged
{
private bool _isSelected;
private double? _karat;
private bool _passed;
public string TestID { get; set; }
public string Label1 { get; set; }
public string Label2 { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
public string HasPassed { get { return Passed ? "Yes" : "No"; } }
public Brush PassColor
{
get
{
return Brushes.Red;
}
}
public bool Passed
{
get { return _passed; }
set
{
_passed = value;
NotifyPropertyChanged();
}
}
public bool Final { get; set; }
public DateTime? TestDate { get; set; }
public Double RealTime { get; set; }
public string JTVID { get; set; }
public int AnalysisID { get; set; }
public List<ElementResults> Elements { get; set; }
public double Karat
{
get
{
if (_karat == null)
_karat = CalculateKarat();
return _karat.Value;
}
set { _karat = value; }
}
public bool PlatingAlert
{
get
{
return Karat < 7.5;
}
}
public bool IsSelected
{
get { return _isSelected; }
set { _isSelected = value; NotifyPropertyChanged(); }
}
public bool PotentialCoating { get; set; }
private double CalculateKarat()
{
if (Elements == null || Elements.Count == 0) return 0;
return Elements.Where(ex => ex.Name.ToLower().Trim() == "au").Select(ex => ex.Level).FirstOrDefault();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
答案 0 :(得分:3)
您正在使用来自WinForms的System.Drawing.Brush
,但您应该使用WPF System.Windows.Media.Brush
。将您的代码更改为:
using System.Windows.Media;
public Brush PassedColor
{
get { return new SolidColorBrush(Colors.Red); }
}
或
public Brush PassedColor
{
get { return Brushes.Red; }
}
也许从引用的程序集中删除System.Drawing
。然后你会立即发现所有这些缺陷。