WPF MVVM Visual Tree绑定无法绑定

时间:2013-01-21 20:07:26

标签: c# wpf xaml data-binding mvvm

我正在尝试绑定到我的viewmodel上的命令。我在视觉树上使用了一个事件触发器。我尝试过尝试绑定它的RelativeSource,FindAncestor和AncestorType的许多变体。每次我得到绑定路径表达式错误。

这是我的xaml文档大纲:

<Window>
   <Grid>
      <GridView>
         <HierarchyChildTemplate>
             <DataTemplate>
                  <TabControl>
                      <TabItem>
                          <GridView>
                              <RowDetailsTemplate>
                                 <TabControl>
                                     <!--trying to bind a event trigger here to a command on the viewModel -->

以下是我尝试过的绑定示例:

<i:Interaction.Triggers>
      <i:EventTrigger EventName="SelectionChanged">
          <i:InvokeCommandAction Command="{Binding Path=SelectionChangedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}}"/>
      </i:EventTrigger>
</i:Interaction.Triggers>

如何从xaml中注明的位置绑定此命令?

2 个答案:

答案 0 :(得分:0)

根据您的可视树和您在评论中写的内容(我还没有测试过):

<i:Interaction.Triggers>
  <i:EventTrigger EventName="SelectionChanged">
      <i:InvokeCommandAction Command="{Binding Path=DataContext.SelectionChangedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>
  </i:EventTrigger>
</i:Interaction.Triggers>

那就是说,我建议在这种情况下使用命名绑定....给最顶层的网格(或原始窗口)命名,例如:

<Window Name="MainWindow">
  ....

然后,您可以使用ElementName

进行绑定
<i:InvokeCommandAction Command="{Binding Path=DataContext.SelectionChangedCommand, 
                                         ElementName=MainWindow}"/>

关于您在评论中所说的内容(AncestorType到达了错误的网格),使用AncestorLevel=2可以帮助您绑定到最顶层的网格。

答案 1 :(得分:0)

结束尝试这个并且它有效:

<i:Interaction.Triggers>
  <i:EventTrigger EventName="SelectionChanged">
     <i:InvokeCommandAction Command="{Binding Path=DataContext.SelectionChangedCommand, 
         RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=2,AncestorType={x:Type GridView}}}"/>
   </i:EventTrigger>
</i:Interaction.Triggers>     

这里的关键点是使用DataContext和AncestorLevel = 2来命令命令。