Quantcast
Channel: Extended WPF Toolkit™ Community Edition
Viewing all articles
Browse latest Browse all 4964

New Post: Applying Styles to each column in Grid Dynamically

$
0
0
Hi,

In your example, each row contains a Foreground. When you set the Column[1].CellContentTemplate, to a DataTemplate binding on row.Foreground, it will work. But if you try to use the same CellContentTemplate on Column[2], the row is the same, with the same Foreground, so will be similar the Column[1]'s foreground. And this is the same for all Font properties.

An idea is to reset the Column's CellContentTemplate. So you pre-define some DataTemplates in the Resources (TextBlock with Foreground, FontFamily...). When you need to change the Display of items in Column[1], you just get the wanted DataTemplate from the resource (or build it in code-behind) and apply it on column[1] :
//Get the DataTemplate in Resources or create one in code-behind
DataTemplate newTemplate = this.ResultGrid.Resources[ "test2Template" ] as DataTemplate;
if( newTemplate != null )
{
   this.ResultGrid.Columns[ "FirstName" ].CellContentTemplate = newTemplate;
}
Another option is to define a ViewModel with Foreground and Font properties...as Dependency properties :
public class MyViewModel : DependencyObject
  {
    public Brush Foreground
    {
      get
      {
        return ( Brush )GetValue( ForegroundProperty );
      }
      set
      {
        SetValue( ForegroundProperty, value );
      }
    }

    public static readonly DependencyProperty ForegroundProperty = DependencyProperty.Register( "Foreground", typeof( Brush ), typeof( MyViewModel ),
                                                                  new UIPropertyMetadata(
                                                                  new SolidColorBrush(Colors.Black) ) );
  }
Then in the resource, define as many of these as you have columns ;
<local:MyViewModel x:Key="View1"  Foreground="Green"/> 
The column's CellContentTemplate can then bind to the corresponding ViewModel's properties in its DataTemplate :
<DataTemplate x:Key="test1Template">
                  <TextBlock Text="{Binding}"
                             Foreground="{Binding Foreground, Source={StaticResource View1}}"/>
               </DataTemplate>
When you need to change dynamically those properties, you just change them on the ViewModels that you retrieve from Resources ;
MyViewModel viewModel2 = this.Resources[ "View2" ] as MyViewModel;
      if( viewModel2 != null )
      {
        viewModel2.Foreground = new SolidColorBrush( Colors.Pink );
      }

Viewing all articles
Browse latest Browse all 4964

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>