2014-10-06 124 views
0

我已經定義了實現TriggerAction<UIElement>的類觸發器。 在該課程內,我想訪問ContentControl類型的上下文菜單的父級。 因此我在觸發器類中定義了DependencyProperty類型:ContentControlWPF綁定到來自ContextMenu的元素

public class MoveToEditModeTrigger : TriggerAction<UIElement> 
    { 
     protected override void Invoke(object parameter) 
     { 
      if (ContentControl == null) return; 
      Selector.SetIsSelected(ContentControl, false); 
      ContentControl.Focusable = true; 
     } 

     public ContentControl ContentControl 
     { 
      get { return (ContentControl)GetValue(ContentControlProperty); } 
      set { SetValue(ContentControlProperty, value); } 
     } 
     public static readonly DependencyProperty ContentControlProperty = 
      DependencyProperty.Register("ContentControl", typeof(ContentControl), typeof(MoveToEditModeTrigger), new FrameworkPropertyMetadata(null)); 
    } 

這裏,我想從觸發類來訪問ContentControlContextMenu

<ContentControl Name="contentControl"> 
    <ContentControl.ContextMenu> 
    <ContextMenu> 
     <MenuItem Header="EditText"> 
     <i:Interaction.Triggers> 
     <i:EventTrigger EventName="Click"> 
      <trigger:MoveToEditModeTrigger ContentControl="{Binding ElementName=contentControl}"/> 
     </i:EventTrigger> 
     </i:Interaction.Triggers> 
     </MenuItem> 
    </ContextMenu> 
    </ContentControl.ContextMenu> 
<RichTextBox x:Name="richtxtLeft" Focusable="True" /> 
</ContentControl> 

的問題是,綁定失敗,ContentControl依賴屬性保持爲空。 我已經做了太多沒有成功:

ContentControl="{Binding RelativeSource={RelativeSource AncestorType=ContentControl, Mode=FindAncestor}}" 

而且還試圖用VisualTreeHalper找到ContentControl。 我也嘗試綁定到ContentControl內的RichTextBox,但沒有任何結果。

請問我該如何訪問觸發器類中的ContentControl

+0

上下文菜單不在UI的可視化樹中。它「飛越」你的用戶界面並擁有自己的視覺樹。 – Fratyx 2014-10-06 14:58:05

+0

我明白,我可以如何將它的可視化樹綁定到我的UI中的另一個控件? – Jacob 2014-10-06 15:03:51

+2

您需要綁定到ContextMenu的PlacementTarget屬性。這是上下文菜單中的元素可以到達可視樹的路線。通常,如果您需要訪問特定元素,則將Tag屬性用作元素的臨時存儲,以便簡化綁定。 [我相信這是關於這個問題的典型問題](http://stackoverflow.com/questions/3668654/relativesource-binding-from-a-tooltip-or-contextmenu)。如果它回答你的問題,我們可以將其標記爲重複(不用擔心)。如果沒有,[編輯]並陳述原因。 – Will 2014-10-06 15:14:03

回答

1

問題是上下文菜單,裝飾物,工具提示和其他元素不在應用程序的可視化樹中,它們位於其他一層。爲了解決這個問題,我試圖做的是使用datacontext來創建綁定,爲視圖模型創建綁定,這個視圖模型可以是菜單的視圖模型(datacontext)或窗口的視圖模型,可能是MainViewModel

這樣你可以有,列表或觀察的集合也許,MenuViewModel S(與屬性IsSelected),並在名爲SelectedMenu主視圖模型的項目或者類似的一些事情。並根據視圖模型值/數據更改項目模板或數據模板。希望這個提示幫助。