【问题标题】:WPF MVVM Visual Tree Binding Cannot BindWPF MVVM 可视化树绑定无法绑定
【发布时间】:2013-01-21 20:07:26
【问题描述】:

我正在尝试绑定到我的视图模型上的命令。我正在使用视觉树上的事件触发器。我已经尝试了许多 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 中注明的位置绑定到此命令?

【问题讨论】:

  • 你试过Path=DataContext.SelectionChangedCommand而不是SelectionChangedCommand吗?
  • 是的。这确实给我带来了不同的结果...它将让我进入第一个 GridView 的 DataContext(集合中的一个模型绑定了 GridView),而不是 ViewModel 的 DataContext。
  • 我不相信仅仅因为触发器实际上不在 可视化树 中会起作用。 RelativeSource 绑定遍历可视化树,当您不在其中时很难做到这一点。尝试切换命名元素的相对源,例如在@Blachshma 的答案的第二部分。

标签: c# wpf xaml data-binding mvvm


【解决方案1】:

根据你的可视化树和你在 cmets 中写的(我没有测试过):

<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}"/>

关于您在 cmets 中所说的(即 AncestorType 到达错误的网格),使用 AncestorLevel=2 应该可以帮助您绑定到最顶层的网格。

【讨论】:

  • 尝试了这两种方法,但出于某种奇怪的原因,它们不起作用...相对源选项导致“找不到绑定引用的源”,并且使用 ElementName 进行绑定找不到该元素名称。 ..我认为 ElementName 只能在视觉树上的相同上下文或级别中使用。无论如何..感谢您的帮助,我现在确实找到了一个可行的解决方案,我将发布。
  • Blachshma 我赞成你的第一条评论,因为你让我走上了正确的道路......谢谢!
【解决方案2】:

最终尝试了这个并且成功了:

<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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 2021-03-01
    • 2017-05-01
    相关资源
    最近更新 更多