WPF MVVM 列表视图:是左键双击需要写入事件



我写了更新函数,我想当我双击列表视图中的数据时,数据将显示在文本框中。我搜索并找到许多解决方案,我有一个例子:

`<ListView ItemsSource="{Binding listHocVien}"
           SelectedItem="{Binding SelectedItem, Mode=OneWayToSource}">
      <ListView.InputBindings>
            <MouseBinding MouseAction="LeftDoubleClick" />
      </ListView.InputBindings>
      <ListView.View>
         <GridView>
            <GridViewColumn Header="Name"
                            DisplayMemberBinding="{Binding Name}">
            </GridViewColumn>
         </GridView>
      </ListView.View>
 </ListView>`

但是当我运行应用程序并单击数据时,我只需要单击一次,而不是双击。我必须在互联网上找到解决方案,没有看到有人说要为 LeftDoubleClick 编写事件。那么,我们是否需要将事件写入 LeftDoubleClick?如果是,谁能给我看例子。感谢您的帮助。

您可以使用以下行为:如何将System.Windows.Interactivity添加到项目中?.

这样,您可以创建双击命令并将其绑定到视图模型类。在执行命令时,您可以将文本框的属性设置为所需的文本

在项目中添加后,应在 xaml 代码中引用命名空间。如果将其引用为 i则用于将行为添加到列表视图的代码应如下所示:

在您的 xaml 中:

<TextBox Text ="{Binding Text, UpdateSourceTrigger=PropertyChanged}"/>
<ListView>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDoubleClick">
            <i:InvokeCommandAction Command="{Binding YourCommand}"
                                   CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ListView>

在视图模型中:

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
public class SampleViewModel : INotifyPropertyChanged {
    private string _Text;
    public event PropertyChangedEventHandler PropertyChanged;
    public string Text {
        get { return _Text; }
        set {
            if (_Text != value) {
                _Text = value;
                RaisePropertyChanged();
            }
        }
    }
    public ICommand YourCommand { get; set; }
    public SampleViewModel() {
        YourCommand = new RelayCommand<TType>(YourCommandExecute); // that TType is the type of your elements in the listview
    }

    // Here I will assume that your TType has a property named Description
    private void YourCommandExecute(TType selectedElement) {
        Text = selectedItem.Description;
    }
    public void RaisePropertyChanged([CallerMemberName] propertyName = null) {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

中继命令实现

// Simple Implementation of Generic Relay Command:
public class RelayCommand<T> : ICommand
{
    private Action<T> execute;
    private Func<T,bool> canExecute;
    public event EventHandler CanExecuteChanged;
    public RelayCommand(Action<T> execute,Func<T,bool> canExecute=null)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }
    public bool CanExecute(object parameter)
    {
        return canExecute == null || canExecute((T)parameter);
    }
    public void Execute(object parameter)
    {
        execute((T)parameter);
    }
}

最新更新