I have an WPF image which has a trigger on Load. How can I make it conditional based on a boolean view model property. I mean, if this property is set to true, then I set the trigger. Otherwise, Loaded trigger should not be set on the image.
<Image Source="{DynamicResource ico_spinnerDrawingImage}" Width="100">
<Image.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation From="0" To="360" Duration="0:0:1"
Storyboard.TargetProperty="Source.Drawing.Transform.Angle"
RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Image.Triggers>
</Image>
I want to do this by only using XAML syntax, not code behind.
CodePudding user response:
You could try to refer to the following code.
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<TextBox x:Name="tb" Text="{Binding ShouldAnimate,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
<Image Margin="300,200" Width="200" Height="250" Source="C:\Users\Admin\source\repos\1122\TriggerDemo\45.jpg" Tag="{Binding ShouldAnimate}" RenderTransformOrigin="0.5,0.5">
<Image.LayoutTransform>
<RotateTransform Angle="0"/>
</Image.LayoutTransform>
<Image.Style>
<Style TargetType="Image">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=tb,Path=Text, UpdateSourceTrigger=PropertyChanged}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Duration="0:0:1" From='0'
To="145" RepeatBehavior="Forever"
Storyboard.TargetProperty="(LayoutTransform).(RotateTransform.Angle)"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
Codebehind:
public class ViewModel : INotifyPropertyChanged
{
private string _shouldAnimate ;
public string ShouldAnimate
{
get { return _shouldAnimate; }
set
{
_shouldAnimate = value;
OnPropertyChanged("ShouldAnimate");
}
}
public ViewModel()
{
ShouldAnimate = "False";
}
public event PropertyChangedEventHandler PropertyChanged;
internal void OnPropertyChanged([CallerMemberName] string propName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}