You can directly associate any control with the visual state during the initializer itself in xaml. To change state, you need to create one dependency property. hope the code below helps you.
<Grid model:StateManager.VisualStateProperty="{Binding VisibilityState}" > <Grid.RowDefinitions> <RowDefinition Height="48" /> <RowDefinition Height="97" /> <RowDefinition Height="65" /> <RowDefinition Height="297" /> </Grid.RowDefinitions> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="VisibleStateGroup"> <VisualState x:Name="VisibleState"> <Storyboard Duration="0:0:0"> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="(UIElement.Visibility)"> <DiscreteObjectKeyFrame KeyTime="0:0:0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="CollapsedState"> <Storyboard Duration="0:0:0"> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="(UIElement.Visibility)"> <DiscreteObjectKeyFrame KeyTime="0:0:0"> <DiscreteObjectKeyFrame.Value> <Visibility>Collapsed</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Grid Name="myGrid" Grid.Row="0" Grid.ColumnSpan="2" > <Grid.ColumnDefinitions> <ColumnDefinition Width="383*" /> <ColumnDefinition Width="383*" /> </Grid.ColumnDefinitions> <StackPanel Grid.Column="0" Orientation="Horizontal" Margin="0,0,15,0" HorizontalAlignment="Right" VerticalAlignment="Center"> <Label Content="MyName"></Label> </StackPanel> </Grid>
Dependency Property Code for Visual State Change
public class StateManager : DependencyObject { public static string GetVisualStateProperty(DependencyObject obj) { return (string)obj.GetValue(VisualStatePropertyProperty); } public static void SetVisualStateProperty(DependencyObject obj, string value) { obj.SetValue(VisualStatePropertyProperty, value); } public static readonly DependencyProperty VisualStatePropertyProperty = DependencyProperty.RegisterAttached( "VisualStateProperty", typeof(string), typeof(StateManager), new PropertyMetadata((s, e) => { var propertyName = (string)e.NewValue; var ctrl = s as Grid; if (ctrl == null) throw new InvalidOperationException("This attached property only supports types derived from FrameworkElement."); var transitionWorked = System.Windows.VisualStateManager.GoToElementState(ctrl, (string)e.NewValue, true);
source share