Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an Initial VisualState in WPF

When using the VisualStateManager in WPF there can be a requirement to transition to a VisualState on control initialization. As far as I can tell there is no way to declare an initial state in Xaml, leaving you with the limited option of transitioning to the required state in your code behind after initialization.

Using code behind is not always desirable, and if you are using a Binding to control your VisualStates then not always possible.

So the question is: how do you set an initial VisualState in WPF without setting it in the code behind?

like image 524
Richard E Avatar asked Jun 06 '13 07:06

Richard E


1 Answers

Too long for a comment

Binding "should" make no difference. If it works fine from code-behind it's bound to work from xaml unless there is something really weird in the Bindings.

All of blend's actions can be considered as a xaml helper tool. End result is you get some xaml that blend creates for you. If you do not want to use blend. Just add the xaml yourself in VS.

For this very thing the GoToStateAction can be coded such as

<Window ...
        xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        ...>
...
<Button x:Name="button"
        Style="{DynamicResource ButtonStyle1}">
  <i:Interaction.Triggers>
    <i:EventTrigger>
      <ei:GoToStateAction StateName="YourState"
                          TargetObject="{Binding ElementName=button}" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

You'll need the corresponding references in your project as well.

On a side-note do try blend. It has it's advantages in specific places. You prolly would not replace typing xaml directly, but it serves as a good helper tool. Ignoring it completely unless forced to is pointless IMO.

like image 175
Viv Avatar answered Nov 15 '22 04:11

Viv