动画和2路绑定
我正在使用 WPF 动画并遇到一个奇怪的问题。
我有一个 Slider
和一个 TextBox
。 TextBox 使用 2 向绑定绑定到 Slider.Value:
<StackPanel>
<Slider x:Name="MySlider" Minimum="0" Maximum="100" Value="50" />
<TextBox Text="{Binding ElementName=MySlider, Path=Value, Mode=TwoWay}" />
<Button Click="Button_Click">Test</Button>
</StackPanel>
当我拖动滑块时,文本框中的文本会发生变化。当我更改文本框中的文本时,滑块的值会更新,它可以正常工作。
现在我添加一个动画,将 Slider.Value 属性设置为 0。按下按钮时启动它。
private void Button_Click(object sender, RoutedEventArgs e)
{
Storyboard storyboard = new Storyboard();
var animation = new DoubleAnimation();
animation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
animation.To = 0;
Storyboard.SetTarget(animation, MySlider);
Storyboard.SetTargetProperty(animation, new PropertyPath(Slider.ValueProperty));
storyboard.Children.Add(animation);
storyboard.Begin();
}
当我按下按钮时,动画将滑块滚动到 0。文本框也与滑块同步更改为 0。
现在我面临这个问题。动画结束后我无法更改文本框中的文本。我更改文本、移动焦点,并且带有滑块值的文本重置为 0。我仍然可以移动滑块,并且文本框会使用滑块值进行更新。但我无法使用文本框设置滑块值。
我认为当动画停止时,该值会以某种方式冻结在 animation.To
属性中指定的值,但我不知道如何解冻它。或者也许是别的东西?
I'm playing with WPF animation and faced a weird problem.
I have a Slider
and a TextBox
. TextBox is bound to Slider.Value using 2-way binding:
<StackPanel>
<Slider x:Name="MySlider" Minimum="0" Maximum="100" Value="50" />
<TextBox Text="{Binding ElementName=MySlider, Path=Value, Mode=TwoWay}" />
<Button Click="Button_Click">Test</Button>
</StackPanel>
When I drag slider, text in textbox changes. When I change text in textbox, value of slider is updated, it works correctly.
Now I add an animation, which animates Slider.Value property to 0. I start it on button press.
private void Button_Click(object sender, RoutedEventArgs e)
{
Storyboard storyboard = new Storyboard();
var animation = new DoubleAnimation();
animation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
animation.To = 0;
Storyboard.SetTarget(animation, MySlider);
Storyboard.SetTargetProperty(animation, new PropertyPath(Slider.ValueProperty));
storyboard.Children.Add(animation);
storyboard.Begin();
}
When I press button, animation scrolls Slider to 0. TextBox is also changes to 0 synchronously with slider.
And now I face the problem. After animation I cannot change text in the TextBox. I change text, move focus, and the text with slider value resets to 0. I still can move the Slider, and the TextBox updates with the Slider value. But I can't set the Slider value using the TextBox.
I think when animation stops, the value somehow freezes on a value, specified in the animation.To
property, but I can't figure how to unfreeze it. Or maybe it is something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况是因为依赖属性值优先级,这意味着动画设置的值比通过绑定设置的值具有更高的“优先级”。
以下是 MSDN 中关于如何解决此问题的引用:
It happens because of dependency property value precedence, meaning that value set by animation has higher "priority" than value set via binding.
Here is a quote from MSDN on how to workaround this: