我可以找到很多命令鼠标绑定到一个按钮,但是如果我想将一个 mousedown 事件绑定到一个绑定(MVVM 模式)呢?我找不到答案,可能是我看不到的很小的东西,但有人可以帮助我吗?
xml:
<DataTemplate>
<Grid AllowDrop="True">
<Rectangle Width="100" Height="50" RadiusX="4" RadiusY="4" Fill="LightBlue"/>
<Label Content="{Binding EntityName}" MouseDown="{Binding DoSomething}"/>
</Grid>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
mm8*_*mm8 11
您可以使用交互触发器:
<Label Content="{Binding EntityName}" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown" >
<i:InvokeCommandAction Command="{Binding DoSomething}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Label>
Run Code Online (Sandbox Code Playgroud)
更多信息请参考以下博文:https : //blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
您将需要添加对System.Windows.Interactivity.dll的引用。
更新版本(上述包不是由库作者制作的):
有关更多详细信息,请参阅https://devblogs.microsoft.com/dotnet/open-sourcing-xaml-behaviors-for-wpf/
上面评价最高的答案需要访问一个 dll,该 dll 仅在您有 blend 时可用。(如果我理解正确)按照其他一些示例,我编写了一个行为,允许您将命令 (ICommand) 属性绑定到 UIElement。
代码如下:
public static class MouseDownBehavior
{
#region Dependecy Property
private static readonly DependencyProperty MouseDownCommandProperty = DependencyProperty.RegisterAttached
(
"MouseDownCommand",
typeof(ICommand),
typeof(MouseDownBehavior),
new PropertyMetadata(MouseDownCommandPropertyChangedCallBack)
);
#endregion
#region Methods
public static void SetMouseDownCommand(this UIElement inUIElement, ICommand inCommand)
{
inUIElement.SetValue(MouseDownCommandProperty, inCommand);
}
private static ICommand GetMouseDownCommand(UIElement inUIElement)
{
return (ICommand)inUIElement.GetValue(MouseDownCommandProperty);
}
#endregion
#region CallBack Method
private static void MouseDownCommandPropertyChangedCallBack(DependencyObject inDependencyObject, DependencyPropertyChangedEventArgs inEventArgs)
{
UIElement uiElement = inDependencyObject as UIElement;
if (null == uiElement) return;
uiElement.MouseDown += (sender, args) =>
{
GetMouseDownCommand(uiElement).Execute(args);
args.Handled = true;
};
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
执行 :
确保将引用“行为”添加到页面/控件/窗口。示例 - xmlns:behavior="clr-namespace:MyWPFApp.Helper.Behavior"
<Border behavior:MouseDownBehavior.MouseDownCommand="{Binding UploadImageMouseDownCommand, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"></Border>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8126 次 |
| 最近记录: |