问题
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>
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>
I already got a solution by defining ListViewItem
style and replacing the ControlTempalte
of the ListViewItem
. Though, I hope there is an easier solution.
Sincerely, Michael
回答1:
Replacing the ControlTemplate
on ListViewItem
using a style is not a bad solution. In fact, it would probably be my first choice.
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>
...
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);
}
}));
}
This could be expanded to handle multiple bindings, but you get the idea: This class allows you to add an InputBinding inside any style.
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.
回答2:
I was able to work around this by doing the following:
1) I added a reference to the System.Windows.Interactivity
DLL (found it in C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries
)
2) Added this to my XAML file:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
3) Added this inside my ListView:
<ListView ...>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{x:Static local:MainWindow.RoutedCommandEditSelectedRecordWindow}" />
</i:EventTrigger>
</i:Interaction.Triggers>
...
</ListView>
来源:https://stackoverflow.com/questions/2133282/adding-mousebindings-to-items-in-a-databound-wpf-listview