gpt4 book ai didi

wpf - 绑定(bind)到 Storyboard 上的附加行为

转载 作者:行者123 更新时间:2023-12-04 00:26:54 24 4
gpt4 key购买 nike

我为 Storyboard 创建了一个附加的依赖属性,目的是让我能够在 Storyboard Completed 事件触发时调用 ViewModel 上的方法:

public static class StoryboardExtensions
{
public static ICommand GetCompletedCommand(DependencyObject target)
{
return (ICommand)target.GetValue(CompletedCommandProperty);
}

public static void SetCompletedCommand(DependencyObject target, ICommand value)
{
target.SetValue(CompletedCommandProperty, value);
}

public static readonly DependencyProperty CompletedCommandProperty =
DependencyProperty.RegisterAttached(
"CompletedCommand",
typeof(ICommand),
typeof(StoryboardExtensions),
new FrameworkPropertyMetadata(null, OnCompletedCommandChanged));

static void OnCompletedCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
Storyboard storyboard = target as Storyboard;
if (storyboard == null) throw new InvalidOperationException("This behavior can be attached to Storyboard item only.");
storyboard.Completed += new EventHandler(OnStoryboardCompleted);
}

static void OnStoryboardCompleted(object sender, EventArgs e)
{
Storyboard item = ... // snip
ICommand command = GetCompletedCommand(item);
command.Execute(null);
}
}

然后我尝试在 XAML 中使用它,使用绑定(bind)语法:
<Grid>
<Grid.Resources>
<Storyboard x:Key="myStoryboard" my:StoryboardExtensions.CompletedCommand="{Binding AnimationCompleted}">
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:5" />
</Storyboard>

<Style x:Key="myStyle" TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger
Binding="{Binding Path=QuestionState}" Value="Correct">
<DataTrigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource myStoryboard}" />
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>

</Grid.Resources>
<Label x:Name="labelHello" Grid.Row="0" Style="{StaticResource myStyle}">Hello</Label>
</Grid>

这失败了,但有以下异常(exception):

System.Windows.Markup.XamlParseException occurred Message="Cannot convert the value in attribute 'Style' to object of type 'System.Windows.Style'. Cannot freeze this Storyboard timeline tree for use across threads. Error at object 'labelHello' in markup file 'TestWpfApp;component/window1.xaml'



有没有办法让绑定(bind)语法与 Storyboard 的附加 ICommand 属性一起使用?

最佳答案

这是设计使然。如果您有一个可卡住的对象放入样式中,则样式将被卡住以允许跨线程访问。但是您的绑定(bind)本质上是一个表达式,这意味着它不能被卡住,因为数据绑定(bind)是单线程的。

如果您需要这样做,请将触发器放在样式之外的框架元素下,而不是样式中。您可以在 Grid.Triggers 部分执行此操作。这确实有点糟糕,因为您的样式不再完整并且您必须复制触发器,但它是 WPF 中的“设计”功能。

MSDN 社交论坛上的完整答案是 here .

关于wpf - 绑定(bind)到 Storyboard 上的附加行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1444252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com