2013-03-17 59 views
1

我试图绑定到MainWindow的属性,但是从ContextMenu内的DataTemplate。我怎样才能做到这一点?如何绑定到ItemTemplate中的父级UIElement?

  • 我不能使用ElementName,作为文本菜单不是视觉树
  • 我不能使用PlacementTarget的一部分,因为这将得到一种由DataTemplate

    <Window x:Class="WpfApplication24.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <ItemsControl ItemsSource="{Binding Data}"> 
        <ItemsControl.ItemTemplate> 
         <DataTemplate> 
          <Border Padding="5" CornerRadius="10" BorderThickness="1" BorderBrush="Red"> 
           <Border.ContextMenu> 
            <ContextMenu ItemsSource="{Binding <I want to bind to a property of MainWindow here>}"/> 
           </Border.ContextMenu> 
           <TextBlock Text="{Binding}"/> 
          </Border> 
         </DataTemplate> 
        </ItemsControl.ItemTemplate> 
    </ItemsControl> 
    
    产生的UIElement

回答

2

您可以在窗口对象您Border的,然后可以使用PlacementTarget.Tag

<DataTemplate> 
    <Border Padding="5" CornerRadius="10" BorderThickness="1" BorderBrush="Red" 
      Tag="{Binding RelativeSource={RelativeSource FindAncestor, 
                 AncestorType=Window}}"> 
     <Border.ContextMenu> 
      <ContextMenu ItemsSource="{Binding PlacementTarget.Tag.PropertyName, 
             RelativeSource={RelativeSource Self}}"/> 
     </Border.ContextMenu> 
     <TextBlock Text="{Binding}"/> 
    </Border> 
</DataTemplate> 
1

我用什么是简单custom control wrapper例如访问MyContextMenu
......只用一行代码,类似...

public class MyContextMenu : ContextMenu 
{ 
    public override void EndInit() 
    { 
     base.EndInit(); 
     NameScope.SetNameScope(this, NameScope.GetNameScope(App.Current.MainWindow)); 
    } 
} 

...并用它来代替ContextMenu

总是“范围”到MainWindow这可能并不总是最优的 - 但你可以使用ElementName

2)另一种选择是使用NameScope.NameScope="{StaticResource myNameScope}"
NameScope.NameScope似乎是一个最佳的解决方案 - 然而,你不能从它绑定(并且它太'绑定')。
但是,您可以使用{StaticResource ...} - 并且创建一个包装MainWindow范围的类。
类似的,但我发现上面的'较少破坏'(你可以写你通常写的代码)。


了解更多详细看看这个答案(和更多的想法)...

ElementName Binding from MenuItem in ContextMenu
How to access a control from a ContextMenu menuitem via the visual tree?

相关问题