我在Window的Resources部分中有一个DataTemplate,它创建一个带有ContextMenu的TextBlock。我希望能够设置ContextMenu中的MenuItem是否可以从我的Window视图模型中看到。我尝试通过设置ElementName
来访问Window的DataContext,并尝试设置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:路径= DataContext.MenuItemVisible;的DataItem = NULL; target元素是'MenuItem'(Name ='');目标属性是 '可见性'(类型'可见性')
当我在绑定中设置RelativeSource而不是ElementName时:
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ScrollViewer}}
我收到以下错误:
System.Windows.Data错误:4:找不到绑定源 参考'RelativeSource FindAncestor, AncestorType = 'System.Windows.Controls.ScrollViewer', AncestorLevel = '1'”。 BindingExpression:路径= DataContext.MenuItemVisible;的DataItem = NULL; target元素是'MenuItem'(Name ='');目标属性是 '可见性'(类型'可见性')
答案 0 :(得分:5)