[英]How to use the DisplayMemberPath in a ListView with an ItemContainerStyle?
[英]how to use EventToCommand in a ItemContainerStyle?
<ListBox Grid.Row="1" ItemsSource="{Binding Source}" SelectedItem="{Binding SelectedItem,Mode=TwoWay}" DisplayMemberPath="Name">
<ListBox.ItemContainerStyle>
<Style>
<EventSetter Event="ListBoxItem.MouseDoubleClick" Handler="DoubleClick" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
現在就是這樣。 如果要將每個ListBoxItem的DoubleClick事件綁定到RelayCommand怎么辦?
這就是我使用MVVMLight EventToCommand功能的方式。
如果您有doubleclick事件掛鈎。 如果不可用,請使用(preview)mousedown並檢查命令args中的clickCount。 ClickCount為2對應於雙擊。
請注意:我有自己的RelayCommand實現。 MVMMLight工具箱中的一個看上去可能有所不同。
XAML:
<interactivity:Interaction.Triggers>
<interactivity:EventTrigger EventName="MouseDown">
<mvvmLight:EventToCommand PassEventArgsToCommand="True" Command="{Binding MouseDownCommand}"></mvvmLight:EventToCommand>
</interactivity:EventTrigger>
</interactivity:Interaction.Triggers>
ViewModel:
public ICommand MouseDownCommand
{
get
{
if (_mouseDownCommand == null)
{
_mouseDownCommand = new RelayCommand(x => MouseDown(x as MouseButtonEventArgs));
}
return _mouseDownCommand;
}
}
private void MouseDown(MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
// do stuff
}
}
做到這一點的最好方法是只使用在代碼隱藏中編寫的普通事件處理程序。 如果需要,這可以中繼到模型或視圖模型上的方法或命令。
像使用EventToCommand行為這樣的技巧只會使您付出更為復雜的XAML的代價,並且會泄漏內存的風險非常高。 (發生這種情況是因為EventToCommand即使不應該偵聽CanExecuteChanged事件也是如此。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.