WPF DataGrid从DataGridCell样式绑定到当前对象属性
本文关键字:对象 属性 绑定 DataGrid DataGridCell 样式 WPF | 更新日期: 2023-09-27 18:03:00
我下面的例子工作得很好,当Id.Updated
属性为真时,它突出显示Id列中的单元格。
我想知道如何修改绑定表达式Binding="{Binding Id.Updated}"
以便绑定当前IssueElement
对象的Updated
属性,在适当的列中(不仅仅是Id列)
我希望能够做到这一点,只有一个样式的所有列,而不是一个样式的每个列。
下面的示例是DataGrid在我的应用程序中如何工作的简化版本。
DataGrid:
<DataGrid ItemsSource="{Binding IssueList}" AutoGenerateColumns="False" >
<DataGrid.Resources>
<Style x:Key="TestStyle" TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<DataTrigger Binding="{Binding Id.Updated}" Value="True">
<Setter Property="Background" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id.Value}" CellStyle="{StaticResource TestStyle}" />
<DataGridTextColumn Header="Title" Binding="{Binding Title.Value}" CellStyle="{StaticResource TestStyle}" />
<DataGridTextColumn Header="Body" Binding="{Binding Body.Value}" CellStyle="{StaticResource TestStyle}" />
</DataGrid.Columns>
</DataGrid>
集合:
private ObservableCollection<Issue> mIssueList;
public ObservableCollection<Issue> IssueList
{
get { return mIssueList; }
set { mIssueList = value; OnPropertyChanged("IssueList"); }
}
集合使用的类
public class Issue
{
public IssueElement Id { get; set; }
public IssueElement Title { get; set; }
public IssueElement Body { get; set; }
}
public class IssueElement
{
public string Value { get; set; }
public bool Updated { get; set; }
}
Thanks in advance
我不知道你为什么有一个。值,两个。价值,三个。值。我想你说的是我。价值,标题。值和主体。价值,正确吗?
我认为你能做到这一点的唯一方法是使用转换器。下面是一种方法:
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource UpdatedConverter}}" Value="True">
<Setter Property="Background" Value="Green" />
</DataTrigger>
和转换器:
public class UpdatedConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DataGridCell dgc = value as DataGridCell;
if (dgc != null)
{
Issue data = dgc.DataContext as Issue;
if (data != null)
{
DataGridTextColumn t = dgc.Column as DataGridTextColumn;
if (t != null)
{
var binding = t.Binding as System.Windows.Data.Binding;
if (binding != null && binding.Path != null && binding.Path.Path != null)
{
string val = binding.Path.Path.ToLower();
if (val.StartsWith("id"))
return data.Id.Updated;
if (val.StartsWith("title"))
return data.Title.Updated;
if (val.StartsWith("body"))
return data.Body.Updated;
}
}
}
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}