2012-01-07 52 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