我想将 DragCompleted 事件绑定(bind)到我的 ViewModel 的命令之一。我使用 Blend 尝试了以下方法,但它不起作用:
<Slider x:Name="slider" HorizontalAlignment="Left" Margin="41,147,0,0" VerticalAlignment="Top" Width="412">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Thumb.DragCompleted">
<i:InvokeCommandAction Command="{Binding DragCompletedCommand}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</Slider>
但这行不通。当我使用事件的正常绑定(bind)来编码时,它起作用了:
<Slider x:Name="slider" Thumb.DragCompleted="slider_DragCompleted" HorizontalAlignment="Left" Margin="41,147,0,0" VerticalAlignment="Top" Width="412"></Slider>
我尝试搜索但奇怪的是找不到答案。
最佳答案
您可以为此编写一个附加属性,如下所示:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
namespace MyTestApplication
{
internal class SliderExtension
{
public static readonly DependencyProperty DragCompletedCommandProperty = DependencyProperty.RegisterAttached(
"DragCompletedCommand",
typeof(ICommand),
typeof(SliderExtension),
new PropertyMetadata(default(ICommand), OnDragCompletedCommandChanged));
private static void OnDragCompletedCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Slider slider = d as Slider;
if (slider == null)
{
return;
}
if (e.NewValue is ICommand)
{
slider.Loaded += SliderOnLoaded;
}
}
private static void SliderOnLoaded(object sender, RoutedEventArgs e)
{
Slider slider = sender as Slider;
if (slider == null)
{
return;
}
slider.Loaded -= SliderOnLoaded;
Track track = slider.Template.FindName("PART_Track", slider) as Track;
if (track == null)
{
return;
}
track.Thumb.DragCompleted += (dragCompletedSender, dragCompletedArgs) =>
{
ICommand command = GetDragCompletedCommand(slider);
command.Execute(null);
};
}
public static void SetDragCompletedCommand(DependencyObject element, ICommand value)
{
element.SetValue(DragCompletedCommandProperty, value);
}
public static ICommand GetDragCompletedCommand(DependencyObject element)
{
return (ICommand)element.GetValue(DragCompletedCommandProperty);
}
}
}
然后您的 Slider-Definition 看起来像:
<Slider x:Name="slider" HorizontalAlignment="Left" Margin="41,147,0,0" VerticalAlignment="Top" Width="412"
extensions:SliderExtension.DragCompletedCommand="{Binding SlideCompletedCommand}"/>
extensions
是附加属性所在的命名空间。
在您的 ViewModel 中,您有一个名为 SlideCompletedCommand 的 ICommand
-Property,它看起来像:
private ICommand slideCompletedCommand;
public ICommand SlideCompletedCommand
{
get { return slideCompletedCommand ?? (slideCompletedCommand = new RelayCommand(p => SlideCompleted())); }
}
private void SlideCompleted()
{
// Your slide-completed-code here
}
关于wpf - 如何数据绑定(bind) WPF Slider 的 Thumb 的 DragCompleted 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40848343/