Best practice for conditional styling (or Style.Tr

2019-06-28 01:43发布

问题:

I have exhausted my internet searches and cannot seem to find the best practice on styling my Windows Store App XAML elements based on data binding conditions?

<Style.Triggers><DataTrigger>...</DataTrigger></Style.Triggers> doesn't appear to be available on Windows 8 Store Apps like it was in WPF, and the Visual State Manager is just for pre-set interaction states such as MouseOver is it not? How can I dramatically change my UI depending on my underlying View Model?

To create a scenario for a clear answer to this question, what is the best practice / most widely accepted way to change a <TextBlock /> for example from one style to another depending on a data binding condition? I say style, because I know you could use a Converter for something like a colour, but what if my changes become quite complex? For instance adding a border, font size and background colour too?

My second scenario is I want to replace the Data of a <Path /> tag depending on a view model condition, is this also possible? Basically, I have a 'cross' and 'tick' XAML path and would like to swap them out depending on view model property.

I am trying to adhere to MVVM where possible as well, so would also prefer not to be hard-coding style references in my code behind.

Thanks all.

回答1:

The VisualStateManager is what you want. From here:

Manages states and the logic for transitioning between states for controls.

I think that is general enough to cover what you want.

The example from the same link should give you some ideas:

<ControlTemplate TargetType="Button">
  <Grid >
    <VisualStateManager.VisualStateGroups>
      <VisualStateGroup x:Name="CommonStates">

        <VisualStateGroup.Transitions>

          <!--Take one half second to transition to the PointerOver state.-->
          <VisualTransition To="PointerOver" 
                              GeneratedDuration="0:0:0.5"/>
        </VisualStateGroup.Transitions>

        <VisualState x:Name="Normal" />

        <!--Change the SolidColorBrush, ButtonBrush, to red when the
            Pointer is over the button.-->
        <VisualState x:Name="PointerOver">
          <Storyboard>
            <ColorAnimation Storyboard.TargetName="ButtonBrush" 
                            Storyboard.TargetProperty="Color" To="Red" />
          </Storyboard>
        </VisualState>
      </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <Grid.Background>
      <SolidColorBrush x:Name="ButtonBrush" Color="Green"/>
    </Grid.Background>
  </Grid>
</ControlTemplate>

It's important to note that you can also change the state of a VisualStateManager from code. Look at the LayoutAwarePage.cs in the default templates for an example of this.