【问题标题】:Set focus of textbox in context menu - wpf在上下文菜单中设置文本框的焦点 - wpf
【发布时间】:2015-12-19 17:45:13
【问题描述】:

我研究了几种设置焦点的方法,但似乎没有任何效果。我敢肯定有人对此有解决方案。这是一个如此简单的任务。

我想设置当用户右键单击列表框时出现在上下文菜单中的文本框的焦点。我不希望用户每次右键单击时都必须单击文本框。

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox>
            <ListBox.ContextMenu>
                <ContextMenu>
                    <ContextMenu.Template>
                        <ControlTemplate>
                            <Border BorderThickness="2" BorderBrush="sc#1,.1,.1,.1" CornerRadius="4" 
                                    Background="sc#1,.05,.05,.05">

                                <TextBox Grid.Row="0" Margin="4" MinWidth="150" Name="SearchBox" VerticalAlignment="Center">
                                </TextBox>

                            </Border>
                        </ControlTemplate>
                    </ContextMenu.Template>
                </ContextMenu>
            </ListBox.ContextMenu>
        </ListBox>
    </Grid>
</Window>

【问题讨论】:

  • 不是没有,但这是一个非常令人吃惊的 UI 设计。仅仅因为 WPF 允许您这样做并不意味着您应该这样做。文本框有自己的上下文菜单-我没有尝试过,但我很确定在该文本框中单击鼠标右键会导致它消失。你确定这就是你想要的吗?
  • 好吧,如果我要对其进行修改并使其在用户单击“标签”键或其他我可以的东西时弹出用户控件。这会帮助解决问题吗?
  • 我不确定您要解决哪个问题。你是说tab键吗?
  • 文本框每次显示都无法设置焦点的问题
  • 为此,您需要查看 WPF 触发器。有很多例子可用,例如stackoverflow.com/questions/19225443/…

标签: c# wpf xaml


【解决方案1】:

TextBox 的 IsFocused 属性是只读的。这在我们的例子中强制使用方法。

您需要CallMethodAction 行为。好的tutorial 开始。

<TextBox Grid.Row="0" Margin="4" MinWidth="150" Name="SearchBox" VerticalAlignment="Center">
    <i:Interaction.Triggers>
        <ei:PropertyChangedTrigger Binding="{Binding IsOpen, RelativeSource={RelativeSource AncestorType=ContextMenu, Mode=FindAncestor}}">
            <ei:CallMethodAction MethodName="FocusSearchBox" TargetObject="{Binding DataContext, ElementName=SearchBox}"/>
            <ei:ChangePropertyAction PropertyName="Background" Value="Purple"/>
        </ei:PropertyChangedTrigger>
    </i:Interaction.Triggers>
</TextBox>




public void FocusSearchBox()
        {
            TextBox t = (TextBox) CtxMenu.ContextMenu.Template.FindName("SearchBox", CtxMenu.ContextMenu);
            t.Focus();
        }

【讨论】:

    猜你喜欢
    • 2010-11-23
    • 2010-10-10
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    相关资源
    最近更新 更多