我是靠谱客的博主 雪白睫毛,这篇文章主要介绍WPF事件绑定到vm方法方法1方法2(使用mvvmlight框架),现在分享给大家,希望可以做个参考。

方法1

第一步,在前端引入命名空间

复制代码
1
2
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

第二步,前端事件绑定vm中的命令

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<Window x:Class="Wp.WpfDemo.UIL.Views.Windows.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:Wp.WpfDemo.UIL.ViewModels.Windows" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:local="clr-namespace:Wp.WpfDemo.UIL.Views.Windows" mc:Ignorable="d" Title="Window1" Height="450" Width="800" x:Name="wd"> <Window.DataContext> <vm:WindowVMBase /> </Window.DataContext> <Grid></Grid> <i:Interaction.Triggers> <i:EventTrigger EventName="Loaded"> <i:InvokeCommandAction Command="{Binding LoadedCmd}" CommandParameter="{Binding ElementName=wd}" /> </i:EventTrigger> </i:Interaction.Triggers> </Window>

这里有的问题,需要给控件命名

第三步.在vm中定义命令

复制代码
1
2
3
4
5
6
7
8
9
10
11
  public ICommand LoadedCmd => new RelayCommand<Window>((wd) =>         {             wd.MouseMove += (sender, e) =>             {                 if (e.LeftButton == MouseButtonState.Pressed)                 {                     wd.DragMove();                 };             };             wd.MouseDoubleClick += (sender, e) => wd.WindowState = wd.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;         });

方法2(使用mvvmlight框架)

第一步.安装mvvmlight框架

第二步.添加命名空间

复制代码
1
2
3
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:mvvmlight="http://www.galasoft.ch/mvvmlight"

第三步.前端事件绑定vm中的命令

复制代码
1
2
3
4
5
6
   <i:Interaction.Triggers>                             <i:EventTrigger EventName="Loaded">                                 <mvvmlight:EventToCommand Command="{Binding LoadedCmd}"                                                           CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />                             </i:EventTrigger>                         </i:Interaction.Triggers>

第四步.在vm中定义命令

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
public ICommand LoadedCmd => new RelayCommand<Window>((wd) => { wd.MouseMove += (sender, e) => { if (e.LeftButton == MouseButtonState.Pressed) { wd.DragMove(); }; }; wd.MouseDoubleClick += (sender, e) => wd.WindowState = wd.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized; });

 

最后

以上就是雪白睫毛最近收集整理的关于WPF事件绑定到vm方法方法1方法2(使用mvvmlight框架)的全部内容,更多相关WPF事件绑定到vm方法方法1方法2(使用mvvmlight框架)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(118)

评论列表共有 0 条评论

立即
投稿
返回
顶部