1. 程式人生 > 其它 >在ItemsControl.DataTemplate中 ContextMenu 獲取父DataContext

在ItemsControl.DataTemplate中 ContextMenu 獲取父DataContext

技術標籤:C#

根據http://www.voidcn.com/article/p-rtutndyr-bvo.html這篇文章給出的解決方案,我將完整的解決程式碼總結下來

方案1:WPF 4.0或更高版本

使用x:Reference標記擴充套件來與ItemsControl dataContext繫結,在ItemsControl上設定x:Name並使用繫結:

<ItemsControl x:Name="itemsControl">
   ....
   <MenuItem Command="{Binding DataContext.Command,
                        Source={x:Reference itemsControl}}"/>
   ....
</ItemControl>

方案2:WPF 低於4.0

使用Freezable BindingProxy方法:

public class BindingProxy : Freezable
    {
        protected override Freezable CreateInstanceCore() => new BindingProxy();

        public object Data
        {
            get => GetValue(DataProperty);
            set => SetValue(DataProperty, value);
        }

        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
    }
    <UserControl.Resources>
        <extensions:BindingProxy x:Key="BindingProxy" Data="{Binding}" />
    </UserControl.Resources>

    <ItemsControl>
       ....
       <MenuItem Command="{Binding Source={StaticResource BindingProxy},             
                                     Path=Data.Command}"/>
       ....
    </ItemControl>

個人感覺第二種方法更好一點,程式碼更優雅一些