2015-10-22 30 views
2

我是WPF的新手,我試圖在ContentControl中動態地添加一個Button,當點擊時它應該觸發一個命令。我正在使用MVVMLight來處理命令。從ContentControl中的Button觸發命令?

下面我有兩個按鈕的例子。頂部按鈕直接放置在StackPanel中。這個按鈕如預期的那樣觸發命令。

第二個按鈕放在ContentControl中。它可以正確顯示,但是單擊按鈕時Command不會觸發。 我認爲這是因爲綁定不通過DataTemplate向下傳遞,但它似乎工作,如果我使用常規命令而不是MVVMLight RelayCommands。

我不想刪除框架,所以我想知道如果有人知道如何解決它?由於

<Window x:Class="ContentControlExample.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:vm="clr-namespace:ContentControlExample.ViewModel"> 

    <Window.DataContext> 
     <vm:MainViewModel /> 
    </Window.DataContext> 

    <Window.Resources> 
     <DataTemplate x:Key="MyButton" > 
      <Button Content="SUBMIT" Command="{Binding MyCommand}" Width="200" Height="50"/> 
     </DataTemplate> 
    </Window.Resources> 

    <StackPanel> 

     <!--When this button is clicked, the Command executes as expected--> 
     <Button Content="SUBMIT" Command="{Binding MyCommand}" Width="200" Height="50"/> 


     <!--Nothing happens when this button is clicked--> 
     <ContentControl ContentTemplate="{StaticResource MyButton}"/> 
    </StackPanel> 
</Window> 

這裏的視圖模型使用以下命令:

public class MainViewModel : ViewModelBase 
{ 
     public ICommand MyCommand { get; private set; } 

     public MainViewModel() 
     { 
      MyCommand = new RelayCommand(MyCommand_Executed, MyCommand_CanExecute); 
     } 

     private bool MyCommand_CanExecute() 
     { 
      return true; 
     } 

     private void MyCommand_Executed() 
     { 
      MessageBox.Show("The command executed"); 
     } 
    } 
+1

綁定的代理可能會有所幫助。見http://stackoverflow.com/questions/7711275/bind-datagrid-column-visibility-mvvm – dytori

回答

1

這裏的問題是在ContentTemplate隱含的DataContext是Content,這尚未設定任何東西。您需要設置Content一些結合當前彌合DataContext在視覺樹,像這樣:

<ContentControl ContentTemplate="{StaticResource MyButton}" Content="{Binding}"/> 
+0

我希望這是簡單的,但不幸的是,這並沒有改變任何東西 – Karmacon

+0

@Karmacon我說的是***正確** *,如果它不適合你,也許還有另一件***錯誤,你的問題沒有顯示。 –

+0

我在這個問題中包含了所有的代碼,並嘗試了你的建議,但沒有發生任何事情。 – Karmacon

1

另一種解決方案是給你的窗口名稱:

<Window x:Class="ContentControlExample.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:vm="clr-namespace:ContentControlExample.ViewModel" 
    x:Name="_this"> 

然後通過綁定其上下文替代:

<Button Content="SUBMIT" Command="{Binding ElementName=_this, Path=DataContext.MyCommand}" Width="200" Height="50"/> 

這對於像ListViews和ItemControls這樣的東西特別方便,因爲它們的DC設置爲列表元素。請記住,這隻適用於同一視覺樹內的成員,如果情況並非如此(例如彈出菜單等),那麼您需要代理綁定as described in this article

+0

謝謝!您的解決方案效果很好,文章對發生的情況以及如何解決問題提供了一個很好的解釋。 – Karmacon