我的 Window 的 Resources 部分中有一个 DataTemplate,它创建一个带有 ContextMenu 的 TextBlock。我希望能够设置 ContextMenu 中的 MenuItem 在我的 Window 视图模型中是否可见。我尝试通过设置访问窗口的DataContext ElementName
,也尝试设置RelativeSource
,但是这两种方法都导致绑定错误。我不确定我还能尝试什么。
我创建了一个小例子来展示我正在尝试做的事情:
XAML:
<Window x:Class="DataTemplateTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<DataTemplate x:Key="TestDataTemplate">
<TextBlock Text="{Binding}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Test" Visibility="{Binding Path=DataContext.MenuItemVisible, ElementName=Root}"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<ScrollViewer x:Name="Root">
<ItemsControl ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource TestDataTemplate}" />
</ScrollViewer>
后面的代码:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
namespace DataTemplateTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
protected readonly MainWindowViewModel vm;
public MainWindow()
{
InitializeComponent();
vm = new MainWindowViewModel();
DataContext = vm;
}
}
public class MainWindowViewModel : INotifyPropertyChanged
{
private Visibility menuItemVisible = Visibility.Hidden;
public Visibility MenuItemVisible { get { return menuItemVisible; } set { menuItemVisible = value; NotifyPropertyChanged("MenuItemVisible"); } }
public List<string> Items { get; set; }
public MainWindowViewModel()
{
Items = new List<string>() { "Alpha", "Beta", "Gamma" };
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我得到的错误是
System.Windows.Data 错误:4:找不到与引用“ElementName = Root”绑定的源。BindingExpression:Path=DataContext.MenuItemVisible; 数据项=空;目标元素是'MenuItem'(名称='');目标属性是“可见性”(类型“可见性”)
当我在绑定中设置 RelativeSource 而不是 ElementName 时:
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ScrollViewer}}
我收到以下错误:
System.Windows.Data 错误:4:找不到与引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ScrollViewer',AncestorLevel ='1''的绑定源。BindingExpression:Path=DataContext.MenuItemVisible; 数据项=空;目标元素是'MenuItem'(名称='');目标属性是“可见性”(类型“可见性”)