只是一个疯狂的猜测,但它可能是在错误的线程中执行的吗?您可能希望使用调度程序在正确的 (UI) 线程上执行它。
GoToState 在 Button_Click 函数中工作吗?
private void Button_Click(object sender, RoutedEventArgs e)
{
bool b = VisualStateManager.GoToState(this, "State2", false);
}
当您执行代码时是否会调用 TransitionToState?
这将排除任何其他问题。
UPDATE
以下内容对我有用。我在设置背景时遇到了一些问题。首先,这对 UserControl 没有任何影响,其次不可能使用颜色动画更改背景,这就是我更改不透明度的原因。
主页.xaml
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<l:TestControl x:Name="_testSubject"
Grid.Row="0"
l:VisualStates.CurrentState="{Binding State}" />
<UserControl x:Name="_test2Subject"
Height="100"
Grid.Row="1"
l:VisualStates.CurrentState="{Binding State}">
<Grid x:Name="aLayoutRoot"
Background="Wheat">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="State2">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="aLayoutRoot"
Storyboard.TargetProperty="Opacity"
From="1"
To="0"
Duration="0:0:2"
AutoReverse="True" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</UserControl>
<Button Click="Button_Click"
Content="Click"
Grid.Row="2" />
</Grid>
测试控件.xaml
<UserControl x:Class="PhoneApp1.TestControl"
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"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="480" d:DesignWidth="480">
<Grid x:Name="LayoutRoot" Background="Wheat">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="State2">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="LayoutRoot"
Storyboard.TargetProperty="Opacity"
From="1"
To="0"
Duration="0:0:2"
AutoReverse="True" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</UserControl>
Test.cs / TransitionToState 方法
private static void TransitionToState(object sender, DependencyPropertyChangedEventArgs args)
{
UserControl c = sender as UserControl;
if (c != null && args.NewValue != null)
{
bool b = VisualStateManager.GoToState(c, (string)args.NewValue, true);
var a = b;
}
}
主页.cs
public MainPage()
{
InitializeComponent();
_testSubject.DataContext = new Test();
_test2Subject.DataContext = new Test();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((Test)_testSubject.DataContext).State = "State2";
((Test)_test2Subject.DataContext).State = "State2";
}
我还建议使用 ControlTemplates 来分配 VisualStates,而不是直接在控件上定义它们。这将为您提供更大的灵活性、更好的维护等。
希望这可以帮助。