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 GridView
s.
And now i want to give somebody the possibility to style the GridView
s 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???
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.
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}"
If you don't want to do it via code-behind then you can use XAML.
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
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}"
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}"