Search code examples
c#wpfuser-controlswpf-controlsforeground

Setting ForegroundColor in a UserControl


I am writing a User Control in WPF and this on is my first own Control. For your Information I am using Telerik controls.

My User Control is only a Grid which contains only contains 2 GridViews. And now i want to give somebody the possibility to style the GridViews by setting a foreground and a background.

Both I set by this way:

Background="{Binding ElementName=Grid, Path=DarkBackground}"
Foreground="{Binding ElementName=Grid, Path=LightForeground}"

My code behind is:

public static DependencyProperty LightForegroundProperty = DependencyProperty.Register( "LightForeground", typeof( Brush ), typeof( ParameterGrid ) );
public Brush LightForeground
{
  get
  {
    return (Brush)GetValue( LightForegroundProperty );
  }
  set
  {
    SetValue( LightForegroundProperty, value );
  }
}

public Brush DarkBackground
{
  get
  {
    return (Brush)GetValue( DarkBackgroundProperty );
  }
  set
  {
    SetValue( DarkBackgroundProperty, value );
  }
}

The problem is that the my foreground, background values are ignored while running. To set a fix value to the Foreground brings the expected result.

I didn't find my mistake, has anybody an idea???


Solution

  • So to clarify...you have a UserControl with a Grid inside and 2 GridViews.

    To refer to the dependency properties on your UserControl...it can be done in different ways.

    Setting DataContext to Self (code-behind)

    In the constructor of your UserControl set the DataContext to point to your UserControl instance.

    DataContext = this;
    

    Then access your properties like so:

    Background="{Binding DarkBackground}"
    Foreground="{Binding LightForeground}"
    

    Setting DataContext to Self (XAML)

    If you don't want to do it via code-behind then you can use XAML.

    <UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
    

    Use a Name on your UserControl and ElementName to refer to it

    Put x:Name="MyUserControl" on your UserControl, and then refer to it with ElementName.

    Background="{Binding ElementName=MyUserControl, Path=DarkBackground}"
    Foreground="{Binding ElementName=MyUserControl, Path=LightForeground}"
    

    Use RelativeSource to tell the Binding the source of the properties.

    Specify the "source" of the Binding by using RelativeSource to hunt for the UserControl in the tree.

    Background="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DarkBackground}"
    Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=LightForeground}"