2016-05-12 75 views
0

不點火ICommand的WPF按鈕命令我有一個按鈕查看如下:在視圖模型

<Button Grid.Column="2" Grid.Row="1" Content="Test" Margin="10,4" 
     Command="{Binding DataContext.CmdTestButtonClicked}" 
     CommandParameter="{Binding}" /> 

在視圖中的代碼隱藏,我設置的DataContext到視圖模型:

public GlobalSettings() 
{ 
    InitializeComponent(); 

    ... 

    DataContext = Helpers.IoCHelper.GlobalSettingsVM; 

    ... 
} 

public class GlobalSettingsVM : CollectionViewModel<GlobalSettings> { ... } 

public abstract class CollectionViewModel<TModel> : IInstallModuleViewModel, INotifyPropertyChanged, 
     INotifyDataErrorInfo where TModel : Model, new() 
{ 
    ... 

    public ICommand CmdTestButtonClicked 
    { 
     get 
     { 
      return _testButtonClicked ?? 
        (_testButtonClicked = new RelayCommand(TestButtonClicked)); 
     } 
    } 

    protected virtual void TestButtonClicked(object o) 
    { 
     // I never get here 
    } 
} 

我沒有任何OTH:我的視圖模型從基類,其暴露ICommand派生呃在我的應用程序中使用這種模式的問題,但是我所有的其他實現都在ListView之內有Button,所以我必須使用RelativeSource={RelativeSource AncestorType={x:Type ListView}}

爲什麼這個命令不會啓動?我是否也需要在這裏設置RelativeSource

+1

我會嘗試改變'Command'的'Button'到'{綁定路徑= CmdTestButtonClicked}'否則你正試圖訪問'的DataContext'尚未設置的按鈕。 –

回答

1

Command="{Binding DataContext.CmdTestButtonClicked}" 

意味着該命令將尋找一個在哪個按鈕被綁定的對象稱爲DataContext屬性。 如果按鈕的DataContext的是這應該工作:

Command="{Binding CmdTestButtonClicked}" 
+0

謝謝,解決了它。我假定Button只會繼承父級的DataContext。我在整個應用程序中的其他地方使用DataContext前綴,而沒有明確地設置控件的DataContext,它可以工作。也許是因爲我也對這些設置了RelativeSource? –

+0

@MarkRichman,的確,每個控件都繼承了它容器的DataContext。是的,當你使用RelativeSource時,你指的是控件本身的一個屬性,而不是綁定的viewmodel。 – Natxo

+0

作爲一條建議,如果您使用RelativeSource來引用DataContext,您(通常)會做錯某些事情,或者這是設計不佳的症狀。 – Natxo

0

您也可以使用MVVM光工具包至極非常方便,並幫助這些情況。

你會得到這樣的事情:

<Button Grid.Column="2" Grid.Row="1" Content="Test" Margin="10,4" 
    <i:Interaction.Triggers> 
      <i:EventTrigger EventName="OnClick" > 
       <Command:EventToCommand Command="{Binding DataContext.CmdTestButtonClicked}" CommandParameter="{Binding}" PassEventArgsToCommand="True"/> 
      </i:EventTrigger> 
     </i:Interaction.Triggers> 
+0

這是如何更簡單或更好? –