WPF中的Command
1 WPF中的Command
public class C_CommandBase : ICommand
{
/// <summary>
/// 要执行的委托动作
/// </summary>
Action<object> mExectuActon;
/// <summary>
/// 取消
/// </summary>
Func<bool> mCanExecute;
public event EventHandler CanExecuteChanged;
public C_CommandBase(Action<object> action) : this(action, null)
{
}
public C_CommandBase(Action<object> action, Func<bool> cancel)
{
mExectuActon = action;
mCanExecute = cancel;
}
public bool CanExecute(object parameter)
{
if (mCanExecute != null)
{
return mCanExecute.Invoke();
}
return true;
}
/// <summary>
/// 执行事件
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter)
{
mExectuActon(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged.Invoke(this, EventArgs.Empty);
}
}
}
2 事件转Command
xmlns:i="http://schemas.microsoft.com/xaml/behaviors" 1、第一种方法 InvokeCommandAction
这种需要New一个Command 我这里使用的Prims
<i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <i:InvokeCommandAction Command="{Binding MouseLeftButtonDownCommand }" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type TextBlock}}}" /> </i:EventTrigger> </i:Interaction.Triggers>
///// <summary>
///// 设置TextBlok控件可以拖拽
///// </summary>
public DelegateCommand<object> MouseLeftButtonDownCommand { get; private set; }
public C_FlowNodeListViewModel()
{
MouseLeftButtonDownCommand = new DelegateCommand<object>(Button_MouseLeftButtonDown);
}
//这里只有一个事件触发者参数,并没有响应者参数,我没有找到应该怎么将响应者参数添加进去
public void Button_MouseLeftButtonDown(object sender)
{
TextBlock txt =sender as TextBlock;
DragDrop.DoDragDrop((DependencyObject)sender, txt.Text, DragDropEffects.Link);
}
2、 第二种 方法 CallMethodAction
TargetObject 表示方法的数据源怎么查找,这种方法有一个好处不用new 一个Command 直接就关联起来,同时还可以有响应参数
第一种只有触发参数
<i:Interaction.Triggers>
<i:EventTrigger EventName="Drop">
<i:CallMethodAction
TargetObject="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl},Path=DataContext}"
MethodName="cans_Drop" />
</i:EventTrigger>
</i:Interaction.Triggers>
public void cans_Drop(object sender, DragEventArgs e)
{
var data= e.Data.GetData(typeof(string));
}
2 事件查找
有的事件直接在ViewMOdel 就可以直接绑定
Command="{Binding DataContext.ControlClick">
有的事件不能直接绑定需要查找,比如在DatGrrid 中的编辑列 这时候就需要查找
Command="{Binding DataContext.ControlClick,RelativeSource={RelativeSource AncestorType=DataGrid,Mode=FindAncestor}}">
在第三方框架的时候最好加上DataContext 否则有时候找不到事件
<Button Margin="5" Content="{Binding Name}" Command="{Binding DataContext.ItemCommand,RelativeSource={RelativeSource AncestorType=Window,Mode=FindAncestor}}"
CommandParameter="{Binding PageName }" />
3 事件参数
CommandParameter="{Binding PageName }"

浙公网安备 33010602011771号