Reputation: 2073
I'm really new to WPF, struggling to get my head around some stuff to do with styles. Firstly, the style doesn't throw any errors anywhere, although i'm still not sure if it's completely correct...so here's my XAML for the style;
edit: The style should allow my custom usercontrol to fade in using a Storyboard and DoubleAnimation
<Application.Resources>
<Style TargetType="{x:Type UserControl}" x:Key="UCStyle">
<Style.Triggers>
<DataTrigger Binding="{Binding Visibility}" Value="Visible">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="UserControl.Opacity" From="0.0" To="1.0" Duration="0:0:3">
</DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Application.Resources>
From here, i'm using a checkbox to add a usercontrol to a canvas' children, as so;
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
UserControlLibrary.UserControl1 userControl = new UserControlLibrary.UserControl1();
userControl.Style = Resources["UCStyle"] as Style;
canvas1.Children.Add(userControl);
}
I read a around on SO, and found a few answers suggesting this is how you apply a style programatically, referencing the key as a style. However, when i run this, the usercontrol doesn't appear to fade in (as the styling would suggest).
Am i missing something vital here? or just being a little silly?
edit 2:
i've modified my checkbox checked event to set visibility to hidden after adding it to canvas, and a new button with a click event that sets visibility to visible, but sadly it didn't fix my problem.
Upvotes: 2
Views: 1107
Reputation: 132548
You're using a DataTrigger
that is binding to UserControl.DataContext.Visibility
, however I'm fairly sure you want to bind to UserControl.Visibility
instead, so you need to use a different binding type.
All bindings by default reference the DataContext
, so to reference something other than the DataContext
, you need to specify a different source for your binding, such as a RelativeSource
binding to Self
<DataTrigger Binding="{Binding Visibility, RelativeSource={RelativeSource Self}}" Value="Visible">
As an alternative, you can use a regular Trigger
instead of a DataTrigger
, which should base the trigger off a Property of the UserControl instead of trying to find the property through a binding.
<Trigger Property="Visibility" Value="Visible">
Upvotes: 2