wpf之通过MVVM绑定MouseEnter
程序员文章站
2022-06-07 15:14:19
...
今天想通过MVVM来绑定MouseEnter事件,现在尝试如下:
首先需要安装包:
再引入命名控件:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
再在VM里面编写鼠标移动的处理事件
<Window x:Class="MvvmMousrEnter.MainWindow"
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:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:local="clr-namespace:MvvmMousrEnter"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid >
<Label Height="160" Width="160" Padding="0" Background="#212121" Foreground="#c9c9c9" VerticalAlignment="Center" HorizontalAlignment="Center"
Content="{Binding Name, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter">
<i:InvokeCommandAction Command="{Binding _CmdMouseEnter}"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeave">
<i:InvokeCommandAction Command="{Binding _CmdMouseLeave}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Label>
</Grid>
</Window>
其实就是两个事件的处理,
看vm模块的处理:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MvvmMousrEnter
{
class My_vm: ObservableObject
{
string _Name;
public string Name
{
get
{
return _Name;
}
set
{
UpdateProperty(ref _Name, value);
}
}
public DelegateCommand _CmdMouseLeave => new DelegateCommand(CmdMouseLeave);
void CmdMouseLeave(object obj)
{
Name = 33333 + "";
}
public DelegateCommand _CmdMouseEnter => new DelegateCommand(CmdMouseEnter);
void CmdMouseEnter(object obj)
{
Name = 44444 + "";
}
}
}
再看结果:达到预期
为了便于大家交流学习,代码提交如下:
https://gitee.com/g0415shenw/Csharp/tree/master/MvvmMousrEnter
下一篇: 实验4-2-4 换硬币 (20分)