命令/事件的綁定
除了數(shù)據(jù)綁定,mvvm中更重要的另一塊就是命令和事件的綁定,wpf中關(guān)于按鈕Button
、菜單項(xiàng)MenuItem
等關(guān)于點(diǎn)擊交互的事件,可以通過命令Command
在ViewModel 中實(shí)現(xiàn)。
基本的命令綁定
示例:在Button上綁定命令
在ViewModel中添加命令和具體執(zhí)行的內(nèi)容
public CommandBase UpdateCommand
{
get
{
return new CommandBase(obj =>
{
Name = NewName;
});
}
}
在Button上進(jìn)行綁定
<Button
Command="{Binding UpdateCommand}"
Content="更新" />
運(yùn)行:
執(zhí)行后:
命令綁定傳入?yún)?shù)
在Button
上定義CommandParameter
屬性
<Button
HorizontalAlignment="Left"
VerticalAlignment="Top"
Command="{Binding UpdateCommand}"
CommandParameter="我是參數(shù)"
Content="更新" />
在ViewModel的命令中,通過obj接收傳入的參數(shù)
public CommandBase UpdateCommand
{
get
{
return new CommandBase(obj =>
{
Name = obj.ToString()+"---"+NewName;
});
}
}
執(zhí)行后的效果:
傳入控件的屬性參數(shù)
將控件屬性或者控件本身(如果傳入控件本身在Path后面填.
—Path=.
)當(dāng)做參數(shù)傳入在CommandParameter
中綁定ElementName
對(duì)應(yīng)控件的name,和屬性名稱
格式:
CommandParameter="{Binding ElementName=ControlName(控件name), Path=PorpertyName(控件屬性名)}"
<Button
Width="62"
Height="22"
Margin="104,182,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Command="{Binding UpdateCommand}"
CommandParameter="{Binding ElementName=TestTxt, Path=Text}"
Content="更新" />
<TextBox
Name="TestTxt"
Width="120"
Margin="76,280,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="TextBox參數(shù)"
TextWrapping="Wrap" />
運(yùn)行效果:
其他事件綁定
除了點(diǎn)擊事件通過Command綁定之外,想要綁定其他命令如MouseEnter
、SelectionChanged
等事件,則需要導(dǎo)入專門的nuget包
安裝Nuget包
安裝Microsoft.Xaml.Behaviors.Wpf
包
支持net framework4.5以上和Net core包括net5,6,7
如果使用舊版本net framework則需要安裝System.Windows.Interactivity.WPF
使用
引入命名空間
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
在控件上添加觸發(fā)器
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter">
<i:InvokeCommandAction Command="{Binding StatusCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
命令跟之前一樣定義
public CommandBase StatusCommand
{
get
{
return new CommandBase(obj =>
{
Status = "鼠標(biāo)進(jìn)入";
});
}
}
效果:在鼠標(biāo)進(jìn)入時(shí),右側(cè)TextBlock顯示鼠標(biāo)進(jìn)入
其他的如ComboBox選擇事件
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding ChangedCommand}" CommandParameter="{Binding ElementName=Cbox, Path=SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
效果:選項(xiàng)變化,Text跟隨變化
特殊事件
如要綁定Button的鼠標(biāo)按下和抬起,不能綁定MouseDown
和MouseUp,
而是要綁定PreviewMouseDown
和PreviewMouseUp
文章來源:http://www.zghlxwxcb.cn/news/detail-484668.html
命令綁定示例-源碼下載文章來源地址http://www.zghlxwxcb.cn/news/detail-484668.html
到了這里,關(guān)于WPF MVVM基礎(chǔ)教程(三)命令/事件的綁定的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!