DisplayStateBehavior not initially applying state

2019-09-05 01:31发布

问题:

I have a listbox item template that contains visual states. I have DisplayStateBehaviors that set the states to either the on/off states. My implementation only 1/2 works. On initial display, the base state is active, regardless of the value in the DataContext. When the data in the DataContext changes, the proper state is activated.

How do I get the proper state displayed on initial display of the listbox.

For security reasons I can not copy/paste XAML or View-Model code.

Edit: While I can't copy/paste the real code, the following skeleton hopefully reproduces the problem.

In a globally visible resource file:

<DataTemplate x:Key="MyObjectItemTemplate">
  <Grid>
    <VisualStateManager.VisualStateGroups>
      ... blend goodness ...
    </VisualStateManager.VisualStateGroups>   
  </Grid>
</DataTemplate>

The data context is passed into the data template by associating it with the ItemsTemplate attribute of the listbox in the main UI.

<ListBox ... ItemTemplate="{DynamicResource MyObjectItemTemplate}" .../>

回答1:

I found my issue. In the event it helps others, what I did to fix it was to extract out the guts of the DataTemplate into a UserControl. This made everything work as I expected. The DataTemplate still exists and is still involved, but it only has one element - the user control. The visual states are all part of the user control.

In a globally visible resource file:

<DataTemplate x:Key="MyObjectItemTemplate">
     <MyNamespace:MyUserControl/>
</DataTemplate>

In a separated file MyUserControl.cs

<UserControl ... x.Class="MyNamespace.MyUserControl" ...>
  <Grid>
    <VisualStateManager.VisualStateGroups>
      ... blend goodness ...
    </VisualStateManager.VisualStateGroups>   
  </Grid>
</UserControl>

The data context is passed into the data template by associating it with the ItemsTemplate attribute of the listbox in the main UI.

<ListBox ... ItemTemplate="{DynamicResource MyObjectItemTemplate}" .../>