WPF EventSetter Handler Command
最近做一个工具,突然发现ListBox和ListView等列表控件的MouseDoubleClick事件有时候是获取不到当前双击的行对象数据的,比如这样写:
<ListBox Grid.Row="" ItemsSource="{Binding DataList}"
MouseDoubleClick="ListBox_MouseDoubleClick"
SelectedItem="{Binding CurrentSelectItem}" Background="AliceBlue">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel Height="" Background="DarkGray" Width="">
<TextBox Text="{Binding Name}" Height="" Width="" Background="DimGray"></TextBox>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListBox listBox = sender as ListBox;
if (listBox == null || listBox.SelectedItem == null)
{
MessageBox.Show("ListBox1双击对象为空...");
}
else
{
var model = listBox.SelectedItem as ListBoxModel;
MessageBox.Show("当前对象为" + model.Name + " " + model.Age);
}
}
双击行就会出现双击的对象为空。
上一篇文章中已经说明怎么解决这个问题:
http://www.cnblogs.com/ligl/p/5629802.html
使用Style中的EventSetter Handler这里就不在更多介绍。
但是今天想要解决的问题是怎么把EventSetter Handler使用Command绑定的方式把Handler事件进行解耦
要使用第三方类库CommandBehavior(AttachedCommandBehavior acb)进行解耦
代码如下:
引用 xmlns:localCommand="clr-namespace:AttachedCommandBehavior"
<Style x:Key="listBox2Item" TargetType="ListBoxItem">
<Style.Setters>
<Setter Property="localCommand:CommandBehavior.Event" Value="MouseDoubleClick"></Setter>
<Setter Property="localCommand:CommandBehavior.Command" Value="{Binding DataContext.DoubleCommand,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type local:WinTest}}}"></Setter>
<Setter Property="localCommand:CommandBehavior.CommandParameter" Value="{Binding RelativeSource={RelativeSource Self}}"></Setter>
</Style.Setters>
</Style>
ViewModel代码如下
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
for (int i = ; i < ; i++)
{
DataList.Add(new ListBoxModel() { Name = "张三" + i.ToString(), Age = + i });
DataList2.Add(new ListBoxModel() { Name = "李四" + i.ToString(), Age = + i });
}
doubleCommand = new SimpleCommand(obj =>
{
ListBoxItem listBoxItem = obj as ListBoxItem;
if (listBoxItem != null)
{
ListBoxModel model = listBoxItem.Content as ListBoxModel;
if (model != null)
{
CurrentSelectItem2 = model;
MessageBox.Show("Command Banding" + model.Name + " " + model.Age);
}
}
//wpftest.ViewModel
MessageBox.Show("Cmd...");
}, o => true);
} public SimpleCommand DoubleCommand
{
get
{
return doubleCommand;
} set
{
doubleCommand = value;
//OnPropertyChanged(new PropertyChangedEventArgs("DoubleCommand"));
}
} private ObservableCollection<ListBoxModel> dataList = new ObservableCollection<ListBoxModel>(); private ObservableCollection<ListBoxModel> _dataList2 = new ObservableCollection<ListBoxModel>(); private ListBoxModel _CurrentSelectItem; private ListBoxModel _CurrentSelectItem2; private SimpleCommand doubleCommand; public ObservableCollection<ListBoxModel> DataList
{
get
{
return dataList;
} set
{
dataList = value;
}
} /// <summary>
/// 当前双击的对象
/// </summary>
public ListBoxModel CurrentSelectItem
{
get
{
return _CurrentSelectItem;
} set
{
_CurrentSelectItem = value;
OnPropertyChanged(new PropertyChangedEventArgs("CurrentSelectItem"));
}
} /// <summary>
/// ListBox2双击的对象
/// </summary>
public ListBoxModel CurrentSelectItem2
{
get
{
return _CurrentSelectItem2;
} set
{
_CurrentSelectItem2 = value;
OnPropertyChanged(new PropertyChangedEventArgs("CurrentSelectItem2"));
}
} public ObservableCollection<ListBoxModel> DataList2
{
get
{
return _dataList2;
} set
{
_dataList2 = value;
}
} public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
}
完整Xaml和CS代码如下:
<Window x:Class="WpfTest.WinTest"
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:local="clr-namespace:WpfTest"
xmlns:localCommand="clr-namespace:AttachedCommandBehavior"
mc:Ignorable="d"
Title="WinTest" Height="" Width="">
<Window.Resources>
<Style TargetType="TextBlock">
<Style.Setters>
<Setter Property="FontSize" Value=""></Setter>
</Style.Setters>
</Style> <Style TargetType="Button">
<Style.Setters>
<Setter Property="localCommand:CommandBehavior.Event" Value="MouseDoubleClick"></Setter>
<Setter Property="localCommand:CommandBehavior.Command" Value="{Binding DoubleCommand}"></Setter>
<Setter Property="localCommand:CommandBehavior.CommandParameter" Value="{Binding Path=DataContext, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type local:WinTest}}}"></Setter>
</Style.Setters>
</Style> <Style x:Key="listBox2Item" TargetType="ListBoxItem">
<Style.Setters>
<Setter Property="localCommand:CommandBehavior.Event" Value="MouseDoubleClick"></Setter>
<Setter Property="localCommand:CommandBehavior.Command" Value="{Binding DataContext.DoubleCommand,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type local:WinTest}}}"></Setter>
<Setter Property="localCommand:CommandBehavior.CommandParameter" Value="{Binding RelativeSource={RelativeSource Self}}"></Setter>
</Style.Setters>
</Style>
<!--<Style x:Key="listBox2Item" TargetType="ListBoxItem">
<Style.Setters>
<EventSetter Event="MouseDoubleClick" Handler="ListBox2_MouseDoubleClick"></EventSetter>
</Style.Setters>
</Style>-->
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=""></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<StackPanel Margin="0 0 20 0">
<TextBlock Text="{Binding CurrentSelectItem.Name}"></TextBlock>
<TextBlock Text="{Binding CurrentSelectItem.Age}"></TextBlock>
</StackPanel> <StackPanel>
<TextBlock Text="{Binding CurrentSelectItem2.Name}">
</TextBlock>
<TextBlock Text="{Binding CurrentSelectItem2.Age}"></TextBlock>
</StackPanel> <Button Content="DoubleClick" ></Button>
</StackPanel> <ListBox Grid.Row="" ItemsSource="{Binding DataList}"
MouseDoubleClick="ListBox_MouseDoubleClick"
SelectedItem="{Binding CurrentSelectItem}" Background="AliceBlue">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel Height="" Background="DarkGray" Width="">
<TextBox Text="{Binding Name}" Height="" Width="" Background="DimGray"></TextBox>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox> <ListBox Grid.Row="" ItemsSource="{Binding DataList2}"
SelectedItem="{Binding CurrentSelectItem2}"
ItemContainerStyle="{StaticResource listBox2Item}"
Background="Silver">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel Height="" Background="DarkOrange" Width="">
<TextBox Text="{Binding Name}" Height="" Width="" Background="DarkCyan"></TextBox>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
using AttachedCommandBehavior;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes; namespace WpfTest
{
/// <summary>
/// WinTest.xaml 的交互逻辑
/// </summary>
public partial class WinTest : Window
{
ViewModel VModel = new ViewModel();
public WinTest()
{
InitializeComponent(); this.DataContext = VModel;
} private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListBox listBox = sender as ListBox;
if (listBox == null || listBox.SelectedItem == null)
{
MessageBox.Show("ListBox1双击对象为空...");
}
else
{
var model = listBox.SelectedItem as ListBoxModel;
MessageBox.Show("当前对象为" + model.Name + " " + model.Age);
}
} private void ListBox2_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListBoxItem listBoxItem = sender as ListBoxItem;
if (listBoxItem == null)
{
MessageBox.Show("ListBox2双击对象为空...");
}
else
{ ListBoxModel model = listBoxItem.Content as ListBoxModel;
if (model != null)
{
VModel.CurrentSelectItem2 = listBoxItem.Content as ListBoxModel;
MessageBox.Show(model.Name + " " + model.Age);
} }
} } public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
for (int i = ; i < ; i++)
{
DataList.Add(new ListBoxModel() { Name = "张三" + i.ToString(), Age = + i });
DataList2.Add(new ListBoxModel() { Name = "李四" + i.ToString(), Age = + i });
}
doubleCommand = new SimpleCommand(obj =>
{
ListBoxItem listBoxItem = obj as ListBoxItem;
if (listBoxItem != null)
{
ListBoxModel model = listBoxItem.Content as ListBoxModel;
if (model != null)
{
CurrentSelectItem2 = model;
MessageBox.Show("Command Banding" + model.Name + " " + model.Age);
}
}
//wpftest.ViewModel
MessageBox.Show("Cmd...");
}, o => true);
} public SimpleCommand DoubleCommand
{
get
{
return doubleCommand;
} set
{
doubleCommand = value;
//OnPropertyChanged(new PropertyChangedEventArgs("DoubleCommand"));
}
} private ObservableCollection<ListBoxModel> dataList = new ObservableCollection<ListBoxModel>(); private ObservableCollection<ListBoxModel> _dataList2 = new ObservableCollection<ListBoxModel>(); private ListBoxModel _CurrentSelectItem; private ListBoxModel _CurrentSelectItem2; private SimpleCommand doubleCommand; public ObservableCollection<ListBoxModel> DataList
{
get
{
return dataList;
} set
{
dataList = value;
}
} /// <summary>
/// 当前双击的对象
/// </summary>
public ListBoxModel CurrentSelectItem
{
get
{
return _CurrentSelectItem;
} set
{
_CurrentSelectItem = value;
OnPropertyChanged(new PropertyChangedEventArgs("CurrentSelectItem"));
}
} /// <summary>
/// ListBox2双击的对象
/// </summary>
public ListBoxModel CurrentSelectItem2
{
get
{
return _CurrentSelectItem2;
} set
{
_CurrentSelectItem2 = value;
OnPropertyChanged(new PropertyChangedEventArgs("CurrentSelectItem2"));
}
} public ObservableCollection<ListBoxModel> DataList2
{
get
{
return _dataList2;
} set
{
_dataList2 = value;
}
} public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
} public class ListBoxModel : INotifyPropertyChanged
{
/// <summary>
/// 姓名
/// </summary>
private string _Name; /// <summary>
/// 年龄
/// </summary>
private int _Age; public string Name
{
get
{
return _Name;
} set
{
_Name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
} public int Age
{
get
{
return _Age;
} set
{
_Age = value;
OnPropertyChanged(new PropertyChangedEventArgs("Age"));
}
} public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
} public event PropertyChangedEventHandler PropertyChanged;
}
}
<Setter Property="localCommand:CommandBehavior.Command" Value="{Binding DataContext.DoubleCommand,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type local:WinTest}}}"></Setter>
关于这个Command的Value绑定要使用FindAncestor进行查找才能解决,不然是绑定不到ViewModel中的DoubleCommand
发个图看看:
关于CommandBehavior代码可以在
http://download.csdn.net/download/doncle000/7029327 下载使用
国外博客http://marlongrech.wordpress.com/2008/12/04/attachedcommandbehavior-aka-acb/
对于SimpleCommad.cs的源文件我增加了两个参数的构造函数:
public SimpleCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
CanExecuteDelegate = canExecute;
ExecuteDelegate = execute;
}
WPF EventSetter Handler Command的更多相关文章
- WPF DataTomplate中Command无效
问题:在DataTomplate中添加一个Button,Button添加Command,但是Command生效. 原因:ItemTemplate的DataContext指代不明,需要改为父类的Data ...
- WPF自学入门(十一)WPF MVVM模式Command命令 WPF自学入门(十)WPF MVVM简单介绍
WPF自学入门(十一)WPF MVVM模式Command命令 在WPF自学入门(十)WPF MVVM简单介绍中的示例似乎运行起来没有什么问题,也可以进行更新.但是这并不是我们使用MVVM的正确方式 ...
- WPF - EventSetter
WPF中添加Event 1. ListBox中添加Event <ListBox x:Name="itemsControl" BorderThickness="0&q ...
- WPF Event 在 Command 中的应用初级篇,支持所有Event 展示松耦合设计的全部代码 - 解决TextBoxBase.TextChanged或者TextBox.TextChanged等类似事件绑定问题。
做过WPF开发的人,都知道做MVVM架构,最麻烦的是Event的绑定,因为Event是不能被绑定的,同时现有的条件下,命令是无法替代Event.而在开发过程中无法避免Event事件,这样MVVM的架构 ...
- WPF自学入门(十一)WPF MVVM模式Command命令
在WPF自学入门(十)WPF MVVM简单介绍中的示例似乎运行起来没有什么问题,也可以进行更新.但是这并不是我们使用MVVM的正确方式.正如上一篇文章中在开始说的,MVVM的目的是为了最大限度地降低了 ...
- WPF命令(Command)介绍、命令和数据绑定集成应用
要开始使用命令,必须做三件事: 一:定义一个命令 二:定义命令的实现 三:为命令创建一个触发器 WPF中命令系统的基础是一个相对简单的ICommand的接口,代码如下: public interfac ...
- [转]WPF命令集 Command
在我们日常的应用程序操作中,经常要处理各种各样的命令和进行相关的事件处理,比如需要复制.粘贴文本框中的内容;上网查看网页时,可能需要返回上一网页查看相应内容;而当我们播放视频和多媒体时,我们可能要调节 ...
- WPF中的Command事件绑定
在项目中使用Command绑定能够使我们的代码更加的符合MVVM模式.不了解的同学可能不清楚,只有继承自ButtonBase类的元素才可以直接绑定Command(Button.CheckBox.Rad ...
- WPF ListBoxItem DataTempldate command 执行问题
今天用到MVVM,在listboxItem中做command处理.因为是要获取数据,修改ListBox模板,但是发现command无法正确执行,写在Item中可以正确执行. 网上也遇到类似问题,但是没 ...
随机推荐
- 避坑宝典:如何选择HTML5游戏引擎
原生手游市场已是红海,腾讯.网易等寡头独霸天下,H5游戏市场成为下一个风口.据笔者所知,很多H5游戏开发团队由于选择引擎不慎导致项目甚至团队夭折. 如何选择适合团队和项目的引擎,笔者通过学习和项目实践 ...
- mod_PHP&fastcgi
从宏观上来看,PHP内核的实现与世界上绝大多数的程序一样,接收输入数据, 做相应处理然后输出(返回)结果. 我们编写的代码就是PHP接收的输入数据,PHP内核对我们编写的代码进行解释和运算, 最后返回 ...
- JDK7学习笔记之基础类型
printf()的基础用法: 变量的基础用法: 字符的输出:
- Oracle索引梳理系列(二)- Oracle索引种类及B树索引
版权声明:本文发布于http://www.cnblogs.com/yumiko/,版权由Yumiko_sunny所有,欢迎转载.转载时,请在文章明显位置注明原文链接.若在未经作者同意的情况下,将本文内 ...
- jq+css+html简单实现导航下拉菜单
相信导航栏下拉菜单是web开发最常见的一个item了.这里就不做介绍了,直接上code. Html部分 <div class="_nav"> <ul id=&qu ...
- SHA-1 加密算法破解现已只需要 10 天
转自:http://www.linuxeden.com/html/news/20151009/163173.html SHA-1是如今很常见的一种加密哈希算法,HTTPS传输和软件签名认证都很喜欢它, ...
- 烂泥:更换ESXI5.0管理网卡及管理IP地址
本文由秀依林枫提供友情赞助,首发于烂泥行天下. 公司的服务器基本上都是在IDC机房里面的,为了更有效的利用服务器性能.所以有几台服务器,安装的是ESXI5.0做成虚拟化. 注意目前这些服务器都是双网卡 ...
- linux中send函数MSG_NOSIGNAL异常消息
最近2周在做ineedle的国舜项目扩展,需要使用socket的tcp连接向对方发送消息,当然需求很简单,只是按照对方要求发送指定格式的消息,程序结构也非常的简单,一对多的client/server模 ...
- linux运维常用命令及知识
1.查找当前目录下所有以.tar结尾的文件然后移动到指定目录: find . -name “*.tar” -exec mv {} ./backup/ ; 查找当前目录30天以前大于100M的LOG文件 ...
- C 运算符优先级
优先级 运算符 名称或含义 使用形式 结合方向 说明 1 [] 数组下标 数组名[常量表达式] 左到右 () 圆括号 (表达式)/函数名(形参表) . 成员选择(对象) 对象.成员名 -& ...