我无法将 ContextMenuItem 的命令绑定到我的父对象。我遵循了以下示例:
- http://www.codeproject.com/Articles/162784/WPF-ContextMenu-Strikes-Again-DataContext-Not-Upda
- 来自 ToolTip 或 ContextMenu 的 RelativeSource 绑定
- WPF:将 ContextMenu 绑定到 MVVM 命令
而且我已经接近了很多,但我仍然收到以下错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'SearchString' property
not found on 'object' ''MainWindow' (Name='root')'.
BindingExpression:Path=Parent.PlacementTarget.Tag.SearchString; DataItem='MenuItem'
(Name=''); target element is 'MenuItem' (Name=''); target property is 'Command' (type
'ICommand')
主窗口类SearchString
定义为:
public partial class MainWindow : Window
{
...
private void SearchString(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
}
但是,显然,永远不会抛出异常。我在 DataTemplate 中定义的菜单如下:
<Window x:Class="CodeNaviWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
Title="View" Height="865" Width="991"
x:Name="root"
>
<Window.Resources>
<DataTemplate x:Key="fileContentView">
<StackPanel>
<Border BorderThickness="3" BorderBrush="BurlyWood">
<avalonEdit:TextEditor
Width="400"
Height="400"
Document="{Binding Path=Document}"
IsReadOnly="True"
Tag="{Binding ElementName=root}">
<avalonEdit:TextEditor.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Search..." Command="{Binding Path=Parent.PlacementTarget.Tag.SearchString, RelativeSource={RelativeSource Self}}" />
</ContextMenu>
</avalonEdit:TextEditor.ContextMenu>
</avalonEdit:TextEditor>
</Border>
</StackPanel>
</DataTemplate>
</Window.Resources>
...
</Window>
谁能看到我哪里出错了?如果我将方法更改为字符串属性,那么我不会收到任何错误,所以我猜测我以某种方式告诉 XAML 期待一个属性,而不是一个方法。