I am currently facing a scenario that I am unsure what is the best way to handle.
Scenario:
- ControlA has 2 two custom visualstates, let’s call them “StateOn” and “StateOff”.
- I now apply a template on ControlA, let’s call it “templateA”.
- “templateA” has one control under it of type ControlB (who’s unaware of StateOn/Off).
- ControlB has a Template that handles the visualstate changes of ControlA, namely, StateOn and StateOff.
Problem:
ControlB does not receive changes to the VisualStates fired on ControlA, thus no visual changes happen.
I think the problem has to do with the root element being a control (ControlB), which doesn’t fire gotostate on the desired states. However, I’m wondering what is the simplest/cleanest way to propagate ControlA’s visualstate changes to ControlB.
Thanks for your help!
Henry
Xaml:-
<UserControl x:Class="VisualStateChangePropagation.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:VisualStateChangePropagation"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<Grid.Resources>
<SolidColorBrush x:Name="Fill_Bg_Red" Color="Red"/>
<SolidColorBrush x:Name="Fill_Bg_Blue" Color="Blue"/>
<ControlTemplate x:Name="templateA" TargetType="Control">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="Common">
<VisualState x:Name="StateOn">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="m_rect"
Storyboard.TargetProperty="(Rectangle.Fill)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource Fill_Bg_Red}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="StateOff"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Rectangle x:Name="m_rect" Fill="{StaticResource Fill_Bg_Blue}"/>
</Grid>
</ControlTemplate>
<ControlTemplate x:Name="templateB" TargetType="Control">
<local:ControlB Template="{StaticResource templateA}"/>
</ControlTemplate>
</Grid.Resources>
<local:ControlA x:Name="m_control1" Template="{StaticResource templateA}" Grid.Column="0"/>
<Button Click="Button_Click" Grid.Column="1" Content="swap"/>
<local:ControlA x:Name="m_control2" Template="{StaticResource templateB}" Grid.Column="2"/>
</Grid>
</UserControl>
code behind:
public class ControlA : Control
{
public void ToggleState()
{
m_isSet = !m_isSet;
UpdateVisualState();
}
private void UpdateVisualState()
{
string targetState = m_isSet ? "StateOn" : "StateOff";
VisualStateManager.GoToState(this, targetState, false);
}
private bool m_isSet = false;
}
public class ControlB : Control
{
}