附加行为以执行ListViewItem的命令

Pau*_*lor 8 c# wpf mvvm

当用户双击列表项时,我试图使用附加行为在我的ViewModel中执行命令.

我已经回顾了很多关于这个主题的文章,并尝试创建一个简单的测试应用程序,但我仍然遇到问题,例如. 使用MVVM从WPF ListView项目中触发双击事件

我的简单测试ViewModel有2个集合,一个返回字符串列表,另一个返回ListViewItem类型列表

public class ViewModel
{
    public ViewModel()
    {
        Stuff = new ObservableCollection<ListViewItem>
                    {
                        new ListViewItem { Content = "item 1" },
                        new ListViewItem { Content = "item 2" }
                    };

        StringStuff = new ObservableCollection<string> { "item 1", "item 2" };
    }

    public ObservableCollection<ListViewItem> Stuff { get; set; }

    public ObservableCollection<string> StringStuff { get; set; }

    public ICommand Foo
    {
        get
        {
            return new DelegateCommand(this.DoSomeAction);
        }
    }

    private void DoSomeAction()
    {
        MessageBox.Show("Command Triggered");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是附加的属性,就像你看到的其他例子:

public class ClickBehavior
{
    public static DependencyProperty DoubleClickCommandProperty = DependencyProperty.RegisterAttached("DoubleClick",
               typeof(ICommand),
               typeof(ClickBehavior),
               new FrameworkPropertyMetadata(null, new PropertyChangedCallback(ClickBehavior.DoubleClickChanged)));

    public static void SetDoubleClick(DependencyObject target, ICommand value)
    {
        target.SetValue(ClickBehavior.DoubleClickCommandProperty, value);
    }

    public static ICommand GetDoubleClick(DependencyObject target)
    {
        return (ICommand)target.GetValue(DoubleClickCommandProperty);
    }

    private static void DoubleClickChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        ListViewItem element = target as ListViewItem;
        if (element != null)
        {
            if ((e.NewValue != null) && (e.OldValue == null))
            {
                element.MouseDoubleClick += element_MouseDoubleClick;
            }
            else if ((e.NewValue == null) && (e.OldValue != null))
            {
                element.MouseDoubleClick -= element_MouseDoubleClick;
            }
        }
    }

    static void element_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        UIElement element = (UIElement)sender;
        ICommand command = (ICommand)element.GetValue(ClickBehavior.DoubleClickCommandProperty);
        command.Execute(null);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的主窗口中,我定义了设置附加行为并绑定到Foo命令的样式

<Window.Resources>
    <Style x:Key="listViewItemStyle" TargetType="{x:Type ListViewItem}">
        <Setter Property="local:ClickBehavior.DoubleClick" Value="{Binding Foo}"/>                 
    </Style>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

定义ListViewItems时工作正常:

<!-- Works -->
<Label Grid.Row="2" Content="DoubleClick click behaviour:"/>        
<ListView Grid.Row="2" Grid.Column="1" ItemContainerStyle="{StaticResource listViewItemStyle}">
    <ListViewItem Content="Item 3" />
    <ListViewItem Content="Item 4" />
</ListView>
Run Code Online (Sandbox Code Playgroud)

当绑定到ListViewItem类型的列表时,这也有效:

<!-- Works when items bound are of type ListViewItem -->
<Label Grid.Row="3" Content="DoubleClick when bound to ListViewItem:"/>        
  <ListView Grid.Row="3" Grid.Column="1" ItemContainerStyle="{StaticResource listViewItemStyle}" ItemsSource="{Binding Stuff}">        
 </ListView>
Run Code Online (Sandbox Code Playgroud)

但这不是:

<!-- Does not work when items bound are not ListViewItem -->
<Label Grid.Row="4" Content="DoubleClick when bound to string list:"/>
  <ListView Grid.Row="4" Grid.Column="1" ItemContainerStyle="{StaticResource listViewItemStyle}" ItemsSource="{Binding StringStuff}">
</ListView>
Run Code Online (Sandbox Code Playgroud)

在输出窗口中,您会看到错误,但发现很难理解错误.
System.Windows.Data错误:39:BindingExpression路径错误:'object'''String'(HashCode = 785742638)'上找不到'Foo'属性.BindingExpression:路径=富; DataItem ='String'(HashCode = 785742638); target元素是'ListViewItem'(Name =''); target属性为'DoubleClick'(类型'ICommand')

所以我的问题是:当你将ListView绑定到Model对象列表时,如何才能将Command正确连接到每个ListViewItem?

谢谢.

Abe*_*cht 8

问题是DataContextfor Binding是字符串.由于Foo字符串类没有属性,因此出现错误.在其他情况下不会发生这种情况,因为它们DataContext从父级继承它们(对于数据项自动生成的容器不会发生这种情况 - 它们DataContext是数据项).

如果你改变你的结合使用父ListViewDataContext,它应该很好地工作:

Value="{Binding DataContext.Foo, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}"
Run Code Online (Sandbox Code Playgroud)