2013-01-21 30 views
0

我想綁定到我的viewmodel上的命令。我正在使用視覺樹上的事件觸發器。我嘗試過很多變種的RelativeSource,FindAncestor和AncestorType試圖綁定它。每當我得到一個綁定路徑表達式錯誤。WPF MVVM可視樹綁定無法綁定

這是我的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?

+1

你嘗試過'Path = DataContext.SelectionChangedCommand'而不是僅僅SelectionChangedCommand嗎? – Blachshma

+0

是的。這確實給了我一個不同的結果......它會讓我進入第一個GridView的DataContext(綁定GridView的集合中的一個模型),但不會傳遞給ViewModel的DataContext。 –

+0

我不相信這只是因爲觸發器實際上不在*可視樹*中。 RelativeSource綁定走在視覺樹上,當你不在它時很難做到這一點。嘗試切換指定元素的相對來源,例如@ Blachshma答案的第二部分。 – Will

回答

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的命令。

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應該可以幫助你綁定到最上面的網格。

+0

嘗試了這些和一些奇怪的原因,他們不工作...相對源選項導致「無法找到綁定參考源」和綁定使用ElementName找不到該元素名稱...我認爲ElementName只能在視覺樹上使用相同的上下文或級別。無論如何..謝謝你的幫助,我確實找到了現在的解決方案,我將發佈。 –

+0

Blachshma我upvoted你的第一個評論,因爲你讓我在正確的軌道..謝謝! –