2013-07-11 6 views
0

У меня возникли проблемы с привязкой команды ContextMenuItem к моему родительскому объекту. Я следовал следующие примеры:Binding Command on ContextMenuItem

И у меня есть много ближе, но я все еще получаю следующее сообщение об ошибке:

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 ожидать свойства, а не метода.

ответ

0

Ответ на мой собственный вопрос здесь, но, надеюсь, это окажется полезным для других. Решение, которое работало для меня было следовать ответы, приведенные здесь: How do I add a custom routed command in WPF?

Мои MainWindow теперь выглядит следующим:

namespace MyNamespace 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      ... 
     } 

     ... 

     private void SearchString(object sender, RoutedEventArgs e) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

    public static class Commands 
    { 
     public static readonly RoutedUICommand SearchString = new RoutedUICommand("Search String", "SearchString", typeof(MainWindow)); 
    } 
} 

И XAML имеет следующие дополнения:

<Window x:Class="CodeNaviWPF.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:CodeNaviWPF" 
     xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit" 
     Title="MyApp" Height="865" Width="991" 
     x:Name="root" 
    > 
    <Window.CommandBindings> 
     <CommandBinding Command="local:Commands.SearchString" Executed="SearchString" /> 
    </Window.CommandBindings> 

    <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="local:Commands.SearchString" /> 
          </ContextMenu> 
         </avalonEdit:TextEditor.ContextMenu> 
        </avalonEdit:TextEditor> 
       </Border> 
      </StackPanel> 
     </DataTemplate> 
    </Window.Resources> 
    ... 
</Window>