WPF路由命令启用与菜单

WPF路由命令启用与菜单

本文介绍了WPF路由命令启用与菜单,但不与按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中,当文本接收到焦点而不是按钮时,将启用菜单。我已经尝试了只是按钮和文本框,但行为是一样的。

 < Window x:Class = WpfPopup.MainWindow
xmlns =http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x =http://schemas.microsoft.com/winfx / 2006 / xaml
Title =MainWindowHeight =350Width =525>
< DockPanel>
< Menu DockPanel.Dock =Top>
< MenuItem Command =ApplicationCommands.Paste/>
< / Menu>
< TextBox BorderBrush =BlackBorderThickness =2Margin =25TextWrapping =Wrapx:Name =text1Height =58Width =203>
MenuItem将不会被启用,直到
此TextBox获取键盘焦点
< / TextBox>
< Button Content =ButtonHeight =23Name =button1Width =93Command =ApplicationCommands.Paste/>
< / DockPanel>
解决方案>

有两种简单的解决方法:



1)使用FocusManager.IsFocusScope:

 < Button Content =ButtonHeight =23Name =button1Width =93Command =ApplicationCommands.PasteFocusManager.IsFocusScope =True/& 

2)手动设置按钮上的CommandTarget:

 < Button Content =ButtonHeight =23Name =button1Width =93Command =ApplicationCommands.PasteCommandTarget ={Binding ElementName = text1}/> 

您可能想知道为什么这适用于菜单项?如果您阅读了 attach的属性你会得到答案:

当你不知道的时候很混乱!


In the following example the menu is enabled when the text receives the focus but not the button. I have tried it with just the button and the text box but the behaviour is the same.

<Window x:Class="WpfPopup.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">
<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem  Command="ApplicationCommands.Paste" />
    </Menu>
    <TextBox BorderBrush="Black" BorderThickness="2" Margin="25" TextWrapping="Wrap" x:Name="text1" Height="58" Width="203" >
        The MenuItem will not be enabled until
        this TextBox gets keyboard focus
    </TextBox>
    <Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" />
</DockPanel>
解决方案

There are two simple ways to fix this:

1) Use FocusManager.IsFocusScope:

    <Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" FocusManager.IsFocusScope="True"/>

2) Set the CommandTarget on the button manually:

<Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" CommandTarget="{Binding ElementName=text1}" />

You are probably wondering why this works for the menu item? If you read the documentation for FocusManager.IsFocusScope attached property you will get the answer:

Very confusing when you don't know that!

这篇关于WPF路由命令启用与菜单,但不与按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:53