Tehila
Tehila

Reputation: 73

Binding an attribute to property of the itemssource collection

I have a data grid. the item source MySource is an observableCollection<myClass>. The class myClass has a property BackgroundOfRow - its type is Brush.

I want to bind the RowBackground attribute to this property in the xaml. how can I do it?

my xaml now is:

<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>

Upvotes: 2

Views: 710

Answers (1)

StepUp
StepUp

Reputation: 38094

You can bind the Background property in the RowStyle of DataGrid:

View:

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

Model:

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

    public Brush BackgroundOfRow { get; set; }
}

ViewModel:

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

Upvotes: 1

Related Questions