1. 程式人生 > >WPF中如何將ListViewItem雙擊事件繫結到Command

WPF中如何將ListViewItem雙擊事件繫結到Command

原文: WPF中如何將ListViewItem雙擊事件繫結到Command

今天的部落格將介紹如何實現ListViewItem雙擊事件繫結到ViewModel中的Command。實現方法藉助了Style中的EventSetter,請看下面的詳細程式碼:

<ListView ItemsSource="{Binding Users}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions
> <ColumnDefinition Width="*" /> <ColumnDefinition Width="2*" /> <ColumnDefinition Width="3*" /> </Grid.ColumnDefinitions> <TextBlock Text="{Binding Name}" VerticalAlignment="Center"
HorizontalAlignment="Center" /> <TextBlock Grid.Column="1" Text="{Binding Birthday}" VerticalAlignment="Center" HorizontalAlignment="Center" /> <TextBlock Grid.Column="2" Text="{Binding Address}" VerticalAlignment="Center" HorizontalAlignment="Center"
/> </Grid> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemContainerStyle> <Style TargetType="{x:Type ListViewItem}"> <Style.Setters> <EventSetter Event="MouseDoubleClick" Handler="OnListViewItemDoubleClick" /> </Style.Setters> </Style> </ListView.ItemContainerStyle> </ListView>

在Code Behind中,

        private void OnListViewItemDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var vm = this.DataContext as MainViewModel;
            
            vm.EditCommand.Execute();
        }

具體的ViewModel中執行需要的操作即可。這樣不會打破MVVM模式。

    class MainViewModel
    {
        private ObservableCollection<User> _users;
        public ObservableCollection<User> Users
        {
            get
            {
                if(_users == null)
                {
                    _users = new ObservableCollection<User>();
                }

                return _users;
            }
        }

        public DelegateCommand EditCommand { get; private set; }

        public MainViewModel()
        {
            Users.Add(new User() { Name = "Tom", Address = "WUXI IPARK", Birthday = new DateTime(2000,1,1) });

            Users.Add(new User() { Name = "Jack", Address = "WUXI IPARK", Birthday = new DateTime(2000, 1, 1) });

            Users.Add(new User() { Name = "Jerry", Address = "WUXI IPARK", Birthday = new DateTime(2000, 1, 1) });

            Users.Add(new User() { Name = "Hellen", Address = "WUXI IPARK", Birthday = new DateTime(2000, 1, 1) });

            EditCommand = new DelegateCommand(Edit);
        }

        private void Edit()
        {
            System.Diagnostics.Debug.WriteLine("MouseDoubleClick Command.");
        }
    }

通過上面的方式就很簡單的將ListView中的MouseDoubleClick事件繫結到Command上。

感謝您的閱讀,程式碼點選這裡下載。