c# - 在上下文菜单中设置文本框的焦点 - wpf

标签 c# wpf xaml

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

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

enter image description here

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>

最佳答案

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();
        }

关于c# - 在上下文菜单中设置文本框的焦点 - wpf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366264/

相关文章:

c# - 如何在 XAML 中访问我的 ListBox 的 DataTemplate(但不是绑定(bind))中的 TextBlock?

c# - 如何在 C# 中将字符串转换为 UTF-8?

c# - 每行设置 XAML Datagrid 文本颜色

c# - 21 岁和 25 岁之间的日期选择器 wpf

.net - WPF 拖放 - DragLeave 何时触发?

c# - XAML 中的枚举转换器

c# - 在 ASP.NET Web 应用程序中隐藏查询字符串

c# - 使用 where 子句时排除字符串的一部分

c# - 如何在后台启动批处理文件并重定向其输出?

c# - 如何以编程方式绑定(bind)到静态属性?