让附加行为起作用

时间:2012-03-23 01:04:38

标签: wpf xaml

我正在尝试了解“附加行为”并遇到了一些问题。我目前使用的文章是:http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/

简而言之,我希望能够“点击”TreeView中的条目,并在记事本中显示一个文件。我有这个代码通过WPF中的命令按钮在记事本中调出一个文件。现在让我们调用这个命令按钮......测试。这是我用来将此按钮绑定到View的XAML。

<TreeView ItemsSource="{Binding Courses}">
  <TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
      <Setter Property="local:CommandBehavior.Event" Value="MouseDoubleClick"/>
      <Setter Property="local:CommandBehavior.Action" Value="{Binding Path=TestIng}"/>
      <Setter Property="local:CommandBehavior.CommandParameter" Value="ShowThis" />
    </Style>
  </TreeView.ItemContainerStyle>
</TreeView>

当我双击TreeView中的一个条目时,它确实执行了代码:“TestIng”,但它在下一行上发生了炸弹:

strategy.Execute(CommandParameter)

实际错误是:

对象引用未设置为对象的intance

所以这告诉我,我可能没有正确设置“CommandParameter”。

这是带有“TestIng”命令按钮定义的模型。

using System.Collections.ObjectModel;
using System.Linq;
using BusinessLib;
using System.Windows.Input;
using System.Windows;
using System;
using System.Collections.Generic;

namespace TreeViewWithViewModelDemo.LoadOnDemand
{
    public class PublicationsViewModel
    {
        readonly ReadOnlyCollection<CourseViewModel> _courses;
        readonly ICommand _searchCommand;

        public PublicationsViewModel(Course[] courses)
        {
            _courses = new ReadOnlyCollection<CourseViewModel>(
                (from course in courses
                 select new CourseViewModel(course))
                .ToList());
            _searchCommand = new TestIng(this);
        }

        public ReadOnlyCollection<CourseViewModel> Courses
        {
            get { return _courses; }
        }

        public ICommand SearchCommand
        {
            get { return _searchCommand; }
        }
    }

    class TestIng : ICommand
    {
        public TestIng(PublicationsViewModel param1)
        {
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        event EventHandler ICommand.CanExecuteChanged
        {
            add { }
            remove { }
        }

        public void Execute(object parameter)
        {
            MessageBox.Show("Into This Here");
        }

        public void ShowThis()
        {
            MessageBox.Show("Into This Here Number2");
        }
    }
}

我知道,鉴于我只给你一部分代码这个事实,你可能不会给我一个确切的答案,但是我想知道你是否会介意给我一些想法如何继续以及接下来我可能会尝试做什么。

我认为错误在于我如何在XAML中定义CommandParameter。我真的不确定我是否理解它是如何工作的,但我认为这是你想要在按下“MouseDoubleClick”时执行的类中的方法。我在ViewModel中有两个方法:

        public void Execute(object parameter)
        public void ShowThis()

我正在使用它进行简单测试...但是这些messagebox.show行没有被执行。就像我说的,我收到了一个错误......

有人可以让我对如何定义提供一些见解:

      <Setter Property="local:CommandBehavior.CommandParameter" Value="ShowThis" />

或者我可以考虑继续进行。我被卡住了......

由于

1 个答案:

答案 0 :(得分:0)

将命令绑定更改为指向SearchCommand而不是TestIng

您的示例代码将TestIng显示为类,而不是属性,并且您需要绑定到属性

相关问题