2012-01-07 48 views
0

我正在搞亂MVVM,而且我用命令綁定了一些按鈕。我在View(= UserControl)中有幾個按鈕,這些按鈕是基於我擁有的對象列表生成的。如何在MVVM中指定命令綁定範圍?

我的代碼如下所示:

(主窗口)

<ItemsControl ItemsSource="{Binding ViewModels}" Margin="12,57,12,12" /> 

(用戶控件)

<ItemsControl ItemsSource="{Binding AllConnections}" Margin="0,34,0,0"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <Button Content="{Binding Password}" Height="23" HorizontalAlignment="Left" Margin="114,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Command="{Binding Path=ConnectCommand}" /> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 

但ConnectCommand不會被調用,我想這是因爲XAML正在尋找它在AllConnections綁定中,而不是它應該在的ViewModels綁定中。我該如何指定?

+0

按鈕內容= 「{綁定密碼}」 - 正確綁定? – ieaglle 2012-01-07 14:31:05

回答

3

您應該使用Relative source來指定祖先。事情是這樣的:

Command = "{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=ViewModel.CommandToBind}" 
+1

我覺得它應該是'DataContext.CommandToBind'? – Ankesh 2012-01-07 14:40:19

+0

是的。這取決於你如何在視圖上設置數據上下文 – ema 2012-01-07 14:42:12