将数据绑定的WPF ListView中的MouseBindings添加到项目中 [英] Adding MouseBindings to Items in a databound WPF ListView
问题描述
当用户点击ListView中的项目时,我试图在我的ViewModel中获取一个命令。当我在XAML中添加一个 ListViewItem
时,我可以添加一个 MouseBinding
到它的 InputBindings
。
I'm trying to get a command in my ViewModel executed when the user clicks on a item in a ListView. When I add a ListViewItem
in XAML I can just add a MouseBinding
to its InputBindings
.
<ListView>
<ListView.View>
<GridView>
<GridViewColumn Header="Test" />
</GridView>
</ListView.View>
<ListViewItem Content="Item 1" >
<ListViewItem.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding DoubleClickCommand}" />
</ListViewItem.InputBindings>
</ListViewItem>
</ListView>
但是如何才能在数据绑定的ListView中获得?
But how can this be achived in a databound ListView?
<ListView ItemsSource="{Binding Patients}">
<ListView.View>
<GridView>
<GridViewColumn Header="Test" />
</GridView>
<!-- How to set the MouseBinding for the generated ListViewItems?? -->
</ListView.View>
我已经得到一个解决方案定义 ListViewItem
样式并替换 ListViewItem
的 ControlTempalte
。虽然,我希望有一个更容易的解决方案。
I already got a solution by defining ListViewItem
style and replacing the ControlTempalte
of the ListViewItem
. Though, I hope there is an easier solution.
真诚,
Michael
Sincerely, Michael
推荐答案
使用样式替换 ListViewItem
上的 ControlTemplate
不是一个坏的解决方案。实际上,这可能是我的第一选择。
Replacing the ControlTemplate
on ListViewItem
using a style is not a bad solution. In fact, it would probably be my first choice.
另一种完成同样类型的方式是在您的 ListViewItem
style:
Another way of accomplishing the same kind is to use a custom attached property on your ListViewItem
style:
<Style TargetType="ListViewItem">
<Setter Property="local:AddToInputBinding.Binding">
<Setter.Value>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding DoubleClickCommand}" />
</Setter.Value>
</Setter>
...
为此,您需要创建MyBindingHandler.AddBinding附加属性:
To do this you need to create the MyBindingHandler.AddBinding attached property:
public class AddToInputBinding
{
public static InputBinding GetBinding(... // create using propa snippet
public static void SetBinding(...
public static readonly DependencyProperty BindingProperty = DependencyProperty.RegisterAttached(
"Binding", typeof(InputBinding), typeof(AddToInputBinding), new PropertyMetadata
{
PropertyChangedCallback = (obj, e) =>
{
((UIElement)obj).InputBindings.Add((InputBinding)e.NewValue);
}
}));
}
这可以扩展为处理多个绑定,但你得到这个想法:这个类允许你添加一个InputBinding里面的任何样式。
This could be expanded to handle multiple bindings, but you get the idea: This class allows you to add an InputBinding inside any style.
这个解决方案可能比你在做什么,因为直接定义了DoubleClick绑定在ListBoxItem上没有在其模板中的另一个控件上。但我认为这主要归结于个人喜好。
This solution may be preferable over what you're doing because the DoubleClick binding is defined directly on the ListBoxItem not on another control inside its template. But I think it mostly just comes down to personal preference.
这篇关于将数据绑定的WPF ListView中的MouseBindings添加到项目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!