Thursday, February 13, 2014

Change WPF DataGridCell background color using IVMultiValueConverter

In a post by codefornothing in which He demonstrate the use of IMultiValueConverter using DataTable: The WPF Datagrid and Me, I decided to create a similar post in which the binding source is of type collection (Observable Collection). I encountered a few issues like how to replace the Binding Path values from binding to a strongly type class instead of DataTable. To get things started, here are the snippets:
Observable Class
Code:
public class StudentList : ObservableCollection<Student>
    {
        public StudentList()
        {
            Add(new Student{ID = 1, Age = 29, Name ="Jerby", Address="Cebu"});
            Add(new Student{ID = 2, Age = 28, Name ="Renz", Address="Cebu"});
            Add(new Student{ID = 3, Age = 23, Name ="Aya", Address="Leyte"});
            Add(new Student{ID = 4, Age = 33, Name ="Jeff", Address="Leyte"});
            Add(new Student{ID = 5, Age = 32, Name ="Greg", Address="Cebu"});
            Add(new Student{ID = 6, Age = 28, Name ="Idsel", Address="Bohol"});
            Add(new Student { ID = 7, Age = 27, Name = "Harold", Address = "Bohol" });
        }
    }

IMulticonverter Class
Code:
    public class DataGridCellHighlighter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
      var cell = (DataGridCell)values[0];
            
            if (cell.Column.SortMemberPath.Equals("Name"))
            {
                if (System.Convert.ToInt32(values[1]) >= 30)
                {
                    return new SolidColorBrush(Colors.CadetBlue);
                }
                else
                {
                    return new SolidColorBrush(Colors.Transparent);
                }
            }

            return new SolidColorBrush(Colors.Transparent);
        } 

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new SystemNotImplementedException();
        }
    }
Window Resource XAML
 <Window.Resources>  
     <src:DataGridCellHighlighter x:Key="DataGridCellHighlighter" />  
     <src:StudentList x:Key="StudentListData" />  
     <Style x:Key="HighlightCellStyle" TargetType="{x:Type DataGridCell}">  
       <Setter Property="DataGrid.Background">  
         <Setter.Value>  
           <MultiBinding Converter="{StaticResource DataGridCellHighlighter}" >  
             <MultiBinding.Bindings>  
               <Binding RelativeSource="{RelativeSource Self}"/>  
               <Binding Path="Age"/>  
             </MultiBinding.Bindings>  
           </MultiBinding>  
         </Setter.Value>  
       </Setter>  
     </Style>  
   </Window.Resources>  

Datagrid XAML
  <DataGrid Grid.Row="0"   
          Grid.Column="0"  
          Grid.RowSpan="3"   
          AutoGenerateColumns="False"   
          CanUserAddRows="False"   
          SelectionMode="Single"  
          SelectionUnit="Cell"  
          ItemsSource ="{Binding Path=StudentItems}"   
          CellStyle="{StaticResource HighlightCellStyle}"  
          Name="dgStudents">  
       <DataGrid.Columns>  
         <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="120" IsReadOnly="True" />  
         <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" MinWidth="100" IsReadOnly="True" />  
         <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" MinWidth="150" IsReadOnly="True" />  
         <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" MinWidth="150" IsReadOnly="True" />  
       </DataGrid.Columns>  
     </DataGrid>  
Cheers!

0 comments:

Post a Comment