我已經定義了實現TriggerAction<UIElement>
的類觸發器。 在該課程內,我想訪問ContentControl
類型的上下文菜單的父級。 因此我在觸發器類中定義了DependencyProperty
類型:ContentControl
。WPF綁定到來自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));
}
這裏,我想從觸發類來訪問ContentControl
內ContextMenu
:
<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
?
上下文菜單不在UI的可視化樹中。它「飛越」你的用戶界面並擁有自己的視覺樹。 – Fratyx 2014-10-06 14:58:05
我明白,我可以如何將它的可視化樹綁定到我的UI中的另一個控件? – Jacob 2014-10-06 15:03:51
您需要綁定到ContextMenu的PlacementTarget屬性。這是上下文菜單中的元素可以到達可視樹的路線。通常,如果您需要訪問特定元素,則將Tag屬性用作元素的臨時存儲,以便簡化綁定。 [我相信這是關於這個問題的典型問題](http://stackoverflow.com/questions/3668654/relativesource-binding-from-a-tooltip-or-contextmenu)。如果它回答你的問題,我們可以將其標記爲重複(不用擔心)。如果沒有,[編輯]並陳述原因。 – Will 2014-10-06 15:14:03