【问题标题】:Binding an attribute to property of the itemssource collection将属性绑定到 itemssource 集合的属性
【发布时间】:2015-12-01 08:55:50
【问题描述】:

我有一个数据网格。 项目来源MySourceobservableCollection<myClass>myClass 类有一个属性BackgroundOfRow - 它的类型是Brush

我想将RowBackground 属性绑定到xaml 中的这个属性。 我该怎么做?

我的 xaml 现在是:

<DataGrid AutoGenerateColumns="False" 
          ItemSource="{Binding Source={StaticResource myViewModel}, Path=MySource}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="First Name" 
                            Binding="{Binding Path=FirstName}" 
                            FontFamily="Arial" 
                            FontStyle="Italic" />
        <DataGridTextColumn Header="Last Name" 
                            Binding="{Binding Path=LastName}"
                            FontFamily="Arial" 
                            FontWeight="Bold" />
    </DataGrid.Columns>
</DataGrid>

【问题讨论】:

标签: c# wpf xaml mvvm binding


【解决方案1】:

可以在DataGridRowStyle中绑定Background属性:

查看:

<DataGrid ItemsSource="{Binding EmployeeColl}>
   <DataGrid.RowStyle>
      <Style TargetType="DataGridRow">
        <Setter Property="Background" Value="{Binding BackgroundOfRow}"/>
      </Style>
   </DataGrid.RowStyle>
</DataGrid>

型号:

public class Employee
{
    public int ID { get; set; }
    public int Name { get; set; }
    public int Surname { get; set; }

    public Brush BackgroundOfRow { get; set; }
}

视图模型:

private ObservableCollection<Employee> employeeColl;
public ObservableCollection<Employee> EmployeeColl
{
   get { return employeeColl; }
   set
     {
       employeeColl = value;
       OnPropertyChanged("EmployeeColl");
     }
}

private void PopulateDataGrid()
{
   employeeColl = new ObservableCollection<Employee>();
   for (int i = 0; i < 100; i++)
   {
     if(i%2==0)
        employeeColl.Add(new Employee() { ID = i, BackgroundOfRow = Brushes.CadetBlue});
     else
        employeeColl.Add(new Employee() { ID = i, BackgroundOfRow = Brushes.Green });
   }
}

【讨论】:

  • 谢谢!这是工作!我不知道使用行样式。你帮了我很多