如何将双击绑定到列表框项目

时间:2018-09-21 15:12:56

标签: c# mvvm uwp

我有两个都包含集合的列表框。当前设置是这样,当在左侧列表框中选择一个项目时,您可以单击按钮以将所选状态添加到右侧列表框中。对于与自定义命令相关联的列表框,有一个添加和删除按钮,其中所选的列表框项目为命令参数。

我想在每个框中添加一个双击功能,以便可以双击项目来添加和删除。我应该能够使用当前命令的execute方法来执行此操作,但是还没有找到将其实现到列表框或listboxitem中的解决方案。我想尽可能地遵循MVVM,但是我已经在当前的execute方法上稍作改动,如下所示,但是我们会提供任何帮助。我还没有找到有关我的特定问题的任何运气。

<ListBox x:Name="List" ItemContainerStyle="{StaticResource ListBoxItem}" DataContext="{StaticResource VM}" 
                            ItemsSource="{Binding Names, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" DisplayMemberPath="Name"
                                 Style="{StaticResource ResourceKey=ListBox}"/>


<Button Content="&gt;&gt;" Margin="5" Style="{StaticResource ResourceKey=MultiButton}" 
                            CommandParameter="{Binding ElementName=List}"
                            Command="{Binding Path=AddSelectedItemCommand}"/>

public void AddSelectedItem(object obj)
    {
        ListBox ListBox = obj as ListBox;
        List<Type> List = new List<Type>();
        if (Name == null)
            Name = new ObservableCollection<Type>();
        if (Name != null)
        {
            foreach (Type item in ListBox.SelectedItems.Cast<object>().ToList())
            {
                List.Add(item);
                Names.Remove(item);
            }

            foreach (Type listItem in List)
            {
                var state = Name.FirstOrDefault(aa => aa.Name == listItem.Name);
                if (state == null)
                {
                    Name.Add(listItem);
                }
            }
        }
        OnPropertyChanged("Name");
        OnPropertyChanged("Names");
    }

2 个答案:

答案 0 :(得分:1)

首先,我想让您知道,您的View模型应该对View本身一无所知,因此对ListBoxes应该一无所知。

对象应该只知道它们所依赖的事物,而不是那些依赖它的事物。因此,ViewModel应该只知道可供任何客户端使用的数据集合。

在您的示例中,当从列表框更改控件时会发生什么-您将不得不更改命令。

因此,首先,您需要更改视图模型的实现,而当前所拥有的不是MVVM。

这是一个完整的清单,应该会对您有所帮助:

<Window x:Class="WpfExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfExample"
        mc:Ignorable="d"
        Title="MainWindow" Height="140" Width="410">
   <Grid>
      <Grid.ColumnDefinitions>
         <ColumnDefinition />
         <ColumnDefinition />
      </Grid.ColumnDefinitions>
      <ListBox ItemsSource="{Binding Path=Names, Mode=OneWay}"
               SelectedItem="{Binding Path=SelectedName}">
         <ListBox.ItemTemplate>
            <DataTemplate>
               <TextBlock Text="{Binding .}">

                  <TextBlock.InputBindings>
                     <MouseBinding MouseAction="LeftDoubleClick" 
                                   Command="{Binding Path=DataContext.MyDoubleClickCommand, 
                                                     RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor} }" />
                  </TextBlock.InputBindings>
               </TextBlock>
            </DataTemplate>
         </ListBox.ItemTemplate>
      </ListBox>
      <ListBox Grid.Column="1" Margin="10,0,0,0" ItemsSource="{Binding Path=NamesTwo, Mode=OneWay}"
               SelectedItem="{Binding Path=SelectedNameTwo}">
         <ListBox.ItemTemplate>
            <DataTemplate>
               <TextBlock Text="{Binding .}">

                  <TextBlock.InputBindings>
                     <MouseBinding MouseAction="LeftDoubleClick" 
                                   Command="{Binding Path=DataContext.MyOtherDoubleClickCommand, 
                                                     RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor} }" />
                  </TextBlock.InputBindings>
               </TextBlock>
            </DataTemplate>
         </ListBox.ItemTemplate>
      </ListBox>
   </Grid>
</Window>

以及背后的代码

namespace WpfExample
{
   /// <summary>
   /// Interaction logic for MainWindow.xaml
   /// </summary>
   public partial class MainWindow : Window
   {
      public MainWindow()
      {
         InitializeComponent();
         DataContext = new MyViewModel();
      }
   }
}

然后是ViewModel,您应该注意,它只修改了供View使用的公开集合

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using Prism.Commands;

namespace WpfExample
{
   public class MyViewModel : INotifyPropertyChanged
   {
      private string _selectedName;
      private string _selectedNameTwo;

      protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
      {
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }

      public ObservableCollection<string> Names { get; } 
         = new ObservableCollection<string>(new List<string>
         {
            "Name1",
            "Name2",
            "Name3",
            "Name4",
            "Name5"
         });

      public ObservableCollection<string> NamesTwo { get; } = new ObservableCollection<string>(new List<string>());

      public string SelectedName
      {
         get { return _selectedName; }
         set { _selectedName = value; OnPropertyChanged(); }
      }

      public string SelectedNameTwo
      {
         get { return _selectedNameTwo; }
         set { _selectedNameTwo = value; OnPropertyChanged(); }
      }

      public ICommand MyOtherDoubleClickCommand
      {
         get
         {
            return new DelegateCommand<string>(name =>
            {
               NamesTwo.Remove(name);
               Names.Add(name);
               SelectedNameTwo = "";
            });
         }
      }

      public ICommand MyDoubleClickCommand
      {
         get
         {
            return new DelegateCommand<string>(name =>
            {
               Names.Remove(name);
               NamesTwo.Add(name);
               SelectedName = "";
            });
         }
      }

      public event PropertyChangedEventHandler PropertyChanged;
   }
}
  

我已将Prism.Core包用于DelegateCommand对象。这不是必需的,我只是为了轻松起见

     

如果在处理ViewModel时不使用它们,则甚至不需要SelectedName和SelectedNameTwo属性。为了完整起见,我将它们包括在内。

  

已编辑:   我最初没有注意到这是针对UWP项目的。我相信以下内容将起作用-尽管此处未进行测试,因为目前我的计算机上尚未设置UWP。我不确定DoubleClick EventName

<Page xmlns:i="using:Microsoft.Xaml.Interactivity"
      xmlns:core="using:Microsoft.Xaml.Interactions.Core>
  <ListBox Grid.Column="1" Margin="10,0,0,0" ItemsSource="{Binding Path=NamesTwo, Mode=OneWay}"
           SelectedItem="{Binding Path=SelectedNameTwo}">
     <ListBox.ItemTemplate>
        <DataTemplate>
           <TextBlock Text="{Binding .}" >
              <i:Interaction.Behaviors>
                 <core:EventTriggerBehavior EventName="DoubleClick">
                    <core:InvokeCommandAction Command="{Binding Path=DataContext.MyDoubleClickCommand, 
                                              RelativeSource={RelativeSource AncestorType=Page, Mode=FindAncestor} }" 
                                              CommandParameter="{Binding .}" />
                 </core:EventTriggerBehavior>
              </i:Interaction.Behaviors>
           </TextBlock>
        </DataTemplate>
     </ListBox.ItemTemplate>
  </ListBox>

答案 1 :(得分:0)

感谢 Bill,因为 UWP 编辑为我指明了一个令人满意的解决方案。

首先,我添加了对 Microsoft.Xaml.Behaviors.Uwp.Managed

的 NuGet 引用

其次,我将 Bill 提到的命名空间添加到我的控件所在的 xaml 中:

<块引用>

xmlns:i="using:Microsoft.Xaml.Interactivity" xmlns:core="使用:Microsoft.Xaml.Interactions.Core"

然后我在我的控件中添加了一些 XAML(在本例中为列表视图):

<ListView ...>
  <i:Interaction.Behaviors>
    <core:EventTriggerBehavior EventName="DoubleTapped">
      <core:InvokeCommandAction Command="{Binding NavigateUpCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}" />
    </core:EventTriggerBehavior>
  </i:Interaction.Behaviors>
  ...
</ListView>

就我而言,这是一个模板化控件 - 并且成功使用了“DoubleTapped”事件名称:)

指挥部是以我所知道的最好的方式建立的;作为控制类中的 ICommand get 访问器提供,该类使用了股票“RelayCommand”实现

相关问题