附加行为以执行ListViewItem的命令

时间:2011-01-07 20:17:02

标签: c# wpf mvvm

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

我已经回顾了很多关于这个主题的文章,并尝试创建一个简单的测试应用程序,但仍然存在问题,例如。 Firing a double click event from a WPF ListView item using MVVM

我的简单测试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");
    }
}

以下是附加属性,您可以看到其他示例:

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);
    }
}

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

<Window.Resources>
    <Style x:Key="listViewItemStyle" TargetType="{x:Type ListViewItem}">
        <Setter Property="local:ClickBehavior.DoubleClick" Value="{Binding Foo}"/>                 
    </Style>
</Window.Resources>

定义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>

当绑定到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>

但这不是:

<!-- 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>

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

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

感谢。

1 个答案:

答案 0 :(得分:8)

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

如果您更改绑定以使用父DataContext的{​​{1}},它应该可以正常工作:

ListView