2011-10-24 29 views
1

我有一個簡單的視圖,我想綁定到我的ViewModel。我目前使用Source =格式進行數據綁定,但是想將其轉換爲在代碼中指定DataContext。在代碼中指定DataContext

這是我和它的工作...

XAML:

<Window.Resources> 
     <local:ViewModel x:Key="ViewModel" /> 
    </Window.Resources> 

    <Button Content="Click"> 
     <local:EventToCommand.Collection> 
      <local:EventToCommandCollection> 
       <local:EventToCommand Event="Click" Command="{Binding Source={StaticResource ViewModel}, Path=ClickCommand, diag:PresentationTraceSources.TraceLevel=High}" /> 
       <local:EventToCommand Event="GotFocus" Command="{Binding Source={StaticResource ViewModel}, Path=GotFocusCommand}" /> 
      </local:EventToCommandCollection> 
     </local:EventToCommand.Collection> 
    </Button> 
</Window> 

視圖模型代碼:

public class ViewModel 
{ 
    public Command ClickCommand { get; set; } 
    public Command GotFocusCommand { get; set; } 

    public ViewModel() 
    { 
     ClickCommand = new Command((obj) => { Execute(obj); return null; }); 
     GotFocusCommand = new Command((obj) => { Execute(obj); return null; }); 
    } 

    void Execute(object param) 
    { 
     if (param != null) 
      System.Windows.MessageBox.Show(param.ToString()); 
     else 
      System.Windows.MessageBox.Show("Execute"); 
    } 
} 

現在我想做的是這在我窗口的代碼背後:

public MainWindow() 
{ 
    InitializeComponent(); 

    DataContext = new ViewModel(); 
} 

並刪除XAML中的Window.Resources部分,但我無法弄清楚如何相應地更改我的綁定字符串。

+0

你是什麼意思是「你不知道」嗎?你沒有訪問XAML代碼?你不能從你在XAML上使用的每一個綁定表達中移除'Source = {StaticResource ViewModel}'部分嗎?如果你這樣做,數據將從'DataContext'本身獲取。 –

+0

請看我下面的評論... – Oliver

+0

@Olivger,根據http://adammills.wordpress.com/2011/02/14/eventtocommand-action-mvvm-glue/什麼@Rachel說應該工作。請參閱您的視覺工作室的'輸出'窗口,並檢查您是否收到任何綁定錯誤 ... –

回答

2

DataContext是默認Source,所以這應該工作:

<local:EventToCommand Event="GotFocus" Command="{Binding GotFocusCommand}" /> 
+0

這將使用父元素的DataContext,在這種情況下是一個按鈕。哪些可能會起作用。但是像UserControls這樣的一些元素不會從父視覺繼承DataContext,因此您必須手動設置它。 –

+0

我的EventToCommandCollection被定義爲EventToCommandCollection:List ,它看起來像從窗口的DataContext傳播停在那裏,所以從來沒有「達到」指定的條目。按照建議更改字符串不起作用。爲什麼DataContext在那裏停留? – Oliver

+0

@ClausJørgensen,你很嚴重錯誤。只要元素屬於可視化樹就可以是用戶控件或任何東西,只要'DataContext'繼承。不繼承數據上下文的東西是ContextMenus,Popups,DataGridColumns。我們必須手動將它們「附加」到可視化樹中,以便它們繼承數據上下文。 –