I am writing a custom user control, called MyUserControl. I have many DependecyProperties for it, which I use in the MainWindow where several MyUserControl are defined multiple times. What I would like to know is how can I create custom Properties that the Triggers/Properties for a style would fire?
For example, if I have a custom property BOOL IsGoing and a custom property MyBackgroung(the background of the UserControl), both defined as :
public bool IsGoing
{
get { return (bool)this.GetValue(IsGoingProperty); }
set { this.SetValue(IsGoingProperty, value); }
}
public static readonly DependencyProperty IsGoingProperty = DependencyProperty.RegisterAttached(
"IsGoing", typeof(bool), typeof(MyUserControl), new PropertyMetadata(false));
public Brush MyBackground
{
get { return (Brush)this.GetValue(MyBackgroundProperty); }
set { this.SetValue(MyBackgroundProperty, value); }
}
public static readonly DependencyProperty MyBackgroundProperty = DependencyProperty.Register(
"MyBackground", typeof(Brush), typeof(MyUserControl), new PropertyMetadata(Brushes.Red));
and if I define my UserControl in MainWindow.xaml, how can I access the Triggers and set MyBackground, depending on whether or not the IsGoing property is true/false? I tried many things, but in essence, I'm trying to achieve something like:
<custom:MyUserControl MyBackground="Green" x:Name="myUC1" Margin="120.433,0,0,65.5" Height="50" Width="250" VerticalAlignment="Bottom" HorizontalAlignment="Left" >
<Style>
<Style.Triggers>
<Trigger Property="IsGoing" Value="True">
<Setter Property="MyBackground" Value="Yellow"/>
</Trigger>
</Style.Triggers>
</Style>
</custom:MyUserControl>
I hope my explanation is good enough for you to understand. I've been working on this for a couple of days now, and I can't seem to find the solution. Thanks for the help!!!
Adrian
Your style should just need to be used as UserControl.Style
and have the correct TargetType
, also default values you intend to change via trigger need to be moved into the style due to precedence:
<custom:MyUserControl.Style>
<Style TargetType="custom:MyUserControl">
<Setter Property="MyBackground" Value="Green"/>
<Style.Triggers>
<Trigger Property="IsGoing" Value="True">
<Setter Property="MyBackground" Value="Yellow"/>
</Trigger>
</Style.Triggers>
</Style>
</custom:MyUserControl.Style>
Whether this actually does anything depends on how you use the properties in the control definition.