1、安裝NuGet
????????
2、在XAML的命名空間引入:
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
3、使用(這里是設(shè)置了一個(gè)Canvas的點(diǎn)擊事件,其它面板也是類(lèi)似這樣設(shè)置):
<Canvas Background="Aqua">
<Rectangle Stroke="Red"
Width="{Binding RectModel.RectangleWidth}"
Height="{Binding RectModel.RectangleHeight}"
Canvas.Left="{Binding RectModel.RectangleLeft}"
Canvas.Top="{Binding RectModel.RectangleTop}"/>
<i:Interaction.Triggers>
<!--EventName是Command指定的Action-->
<i:EventTrigger EventName="MouseDown">
<i:InvokeCommandAction Command="{Binding MouseDownCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Canvas>
? ? ? ? --我這里的ViewModel部分是這樣子的
public SimpleCommand MouseDownCommand { get; private set; }
// 構(gòu)造方法中初始化
MouseDownCommand = new SimpleCommand { DoExecute = new Action<object>(MouseDown) };
/// <summary>
/// 鼠標(biāo)按下的命令執(zhí)行邏輯
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private void MouseDown(object obj)
{
Debug.WriteLine("觸發(fā)Canvas的MouseDown命令");
}
/// SimpleCommand類(lèi)是這樣的:
public class SimpleCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public Action<object> DoExecute { get; set; }
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
if (DoExecute != null)
{
DoExecute(parameter);
}
}
}
4、這樣就可以在ViewModel中直接給這個(gè)Command內(nèi)容了,不用像之前那么麻煩地綁定Command了,這樣更加清晰,Command也可以有花樣地組合
補(bǔ)充:
在Border中使用:
<b:Interaction.Triggers>
<b:EventTrigger EventName="MouseLeftButtonDown">
<!--基于命令-->
<!--<b:InvokeCommandAction Command="{Binding MouseDownCommand}" PassEventArgsToCommand="True"></b:InvokeCommandAction>-->
<!--基于方法-->
<b:CallMethodAction TargetObject="{Binding}" MethodName="DoMouseLeftButtonDown"/>
</b:EventTrigger>
</b:Interaction.Triggers>
基于命令中的:這個(gè)PassEventArgsToCommand起到的作用就是將觸發(fā)事件的參數(shù)傳遞給綁定的Command。(可以獲取鼠標(biāo)點(diǎn)擊位置啊這些)
基于方法的:MethodName中的就是ViewModel里面的方法
這里的Interaction.Triggers是附加屬性文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-759378.html
InvokeCommandAction和CallMethodAction都是附加行為:<b:Interaction.Triggers>
添加了一個(gè)事件觸發(fā)器(EventTrigger
),當(dāng)指定的事件發(fā)生時(shí)(在這里是 MouseLeftButtonDown
),執(zhí)行特定的動(dòng)作(InvokeCommandAction
),這是一個(gè)典型的附加行為。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-759378.html
到了這里,關(guān)于WPF實(shí)現(xiàn)更加靈活綁定復(fù)雜Command(使用Microsoft XAML Behaviors 庫(kù))的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!