我有一个应用程序,其中的某些控件可以“发布”某些键绑定,这些键绑定又出现在上下文帮助中,例如,一个按钮发布 F5 一个键绑定:
<Button Name="PublishKeybinding" Content="Publish my keybindings!">
<Button.InputBindings>
<KeyBinding Command="{Binding TestCommand}" Gesture="F5" />
</Button.InputBindings>
</Button>
并且有上下文帮助将所有已发布的命令显示为可点击列表:
<ListView Name="PublicKeybindingsList" ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Gesture}">
<TextBlock.InputBindings>
<MouseBinding Command="{Binding Command}" Gesture="LeftClick"/>
</TextBlock.InputBindings>
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
命令 work 的(已发布和上下文)实例都可以正确执行,但是在评估PublicKeybindingsList
项的绑定时会记录绑定错误:
System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。 BindingExpression:Path = TestCommand; DataItem ='TestVM'(HashCode = 47530006);目标元素是'KeyBinding'(HashCode = 53182860);目标属性为“命令”(类型为“ ICommand”)
如何“修复”绑定错误?
有关用于重现该问题的完整代码:
public class SomeCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => true;
public void Execute(object parameter)
{
MessageBox.Show("Success!");
}
}
public class TestVM
{
public ICommand TestCommand { get; } = new SomeCommand();
}
public partial class MainWindow : Window
{
public ObservableCollection<KeyBinding> AllCommands { get; } = new ObservableCollection<KeyBinding>();
public MainWindow()
{
InitializeComponent();
PublishKeybinding.DataContext = new TestVM();
PublicKeybindingsList.DataContext = AllCommands;
foreach (var cmd in PublishKeybinding.InputBindings.OfType<KeyBinding>())
{
AllCommands.Add(cmd);
}
}
}
请注意,代码示例是“最小的,可复制的示例”,并且显示的值和/或键绑定没有太大意义。