2012-03-23 18 views
0

我在嘗試瞭解「附加行爲」並遇到了一些問題。我目前使用的文章是:http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/獲取附加行爲來工作

簡而言之,我希望能夠「點擊」TreeView中的一個條目,並在記事本中創建一個文件。我有這個代碼在記事本中通過WPF中的命令按鈕啓動一個文件。現在讓我們調用這個命令按鈕...測試。以下是我用來將此按鈕綁定到視圖的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的項雙擊它確實執行代碼:

strategy.Execute(CommandParameter)

:「測試」,但它的下面一行炸彈

實際的錯誤是:

對象引用不設置到對象的intance

所以這告訴我,我也許已經不成立了「CommandPa rameter「正確。

這裏是模型與「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" /> 

還是什麼我可能考慮才能繼續進行。我卡住了...

感謝

+0

如果您在該行中遇到異常,您提到「strategy」必須爲「null」,參數爲null只會在execute方法內產生影響。 – 2012-03-23 02:06:45

回答

0

更改命令結合指向的SearchCommand代替TestIng

你的示例代碼顯示TestIng爲一類,而不是一個屬性,你需要綁定屬性