我想让用户停止拖动时返回0的滑块。
到目前为止,我有这个:
<Window x:Class="CenteredSliderTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<!--Value="{Binding ZSpeed}"-->
<Slider DockPanel.Dock="Left"
x:Name="ZSlider"
Minimum="-100" Maximum="100"
SelectionStart="-20" SelectionEnd="20"
Orientation="Vertical"
TickFrequency="10"
TickPlacement="TopLeft"
AutoToolTipPlacement="TopLeft"
AutoToolTipPrecision="2"
LargeChange="10"
SmallChange="1"
IsDirectionReversed="True"
Focusable="False"
>
<Slider.Triggers>
<EventTrigger RoutedEvent="LostMouseCapture" SourceName="ZSlider">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="ZSlider"
Storyboard.TargetProperty="Value"
From="{Binding Value, ElementName=ZSlider}"
To="0.0"
Duration="0:0:1.5"
FillBehavior="Stop"
/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Slider.Triggers>
</Slider>
<TextBlock Text="{Binding ZSpeed}" />
</DockPanel>
</Window>
只要我没有将滑块值绑定到我的DependencyProperty ZSpeed,就可以正常工作。
一旦我这样做,滑块就会跳回到原始值,在第二次尝试时,滑块不能再被拖动。
那么我能做什么(最好是在xaml中)才能让动画不仅修改滑块而且还修改ZSpeed属性?
修改
MainWindow中的代码:
public partial class MainWindow : Window
{
public double ZSpeed
{
get { return (double)GetValue(ZSpeedProperty); }
set { SetValue(ZSpeedProperty, value); }
}
// Using a DependencyProperty as the backing store for ZSpeed. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ZSpeedProperty =
DependencyProperty.Register("ZSpeed", typeof(double), typeof(MainWindow), new UIPropertyMetadata(0.0));
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Binding binding = new Binding("Value") { Source = ZSlider };
this.SetBinding(ZSpeedProperty, binding);
}
}
答案 0 :(得分:1)
您可以反转绑定的方向。您可以将Value
绑定到ZSpeed
,而不是将滑块ZSpeed
绑定到Value
。如果Slider要更改ZSpeed
,这也是“自然”绑定方向,但ZSpeed
不会改变。
编辑:如果ZSpeed
是某个数据类MyData
中的依赖项属性,则可以使用以下代码创建绑定:
MyData dataObject = ...
Binding binding = new Binding("Value") { Source = ZSlider };
dataObject.SetBinding(MyData.ZSpeedProperty, binding);
第二次编辑:提起丹尼尔斯的建议,你可以动画ZSpeed
而不是滑块Value
。像以前一样将Value
绑定到ZSpeed
,删除EventTrigger并为LostMouseCapture
添加事件处理程序:
<Slider x:Name="ZSlider" ...
Value="{Binding ZSpeed}"
LostMouseCapture="ZSlider_LostMouseCapture"/>
代码背后:
private void ZSlider_LostMouseCapture(object sender, MouseEventArgs e)
{
DoubleAnimation animation = new DoubleAnimation
{
From = ZSpeed,
To = 0d,
Duration = TimeSpan.FromSeconds(1.5 * Math.Abs(ZSpeed) / 100d),
FillBehavior = FillBehavior.Stop
};
ZSpeed = 0d;
BeginAnimation(ZSpeedProperty, animation);
}
答案 1 :(得分:1)
您应该使用 FillBehavior.HoldEnd
。
编辑:这显然不起作用。您可以在ZSpeed
事件中手动将StoryBoard.Completed
值设置为0。