动态阻止TextBox获得焦点

时间:2011-10-06 07:09:14

标签: c# wpf dynamic textbox focus

我有一个System.Windows.Controls.TextBox我想表现如下:当您点击它时,动态确定TextBox是否得到焦点。这是一个玩具应用程序,其中包含尝试完成此操作的失败:

<!-- MainWindow.xaml -->
<Window x:Class="Focus.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">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Label Name="myLabel" Grid.Row="0" Background="Red"></Label>
        <TextBox Name="myTextbox" Grid.Row="1" Background="Green"></TextBox>
    </Grid>
</Window>

// MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Input;

namespace Focus
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;
        }

        private static readonly Random myRandom = new Random();

        private void myTextbox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            int randomInt = myRandom.Next(0, 2); // 0 or 1
            myLabel.Content = randomInt;
            if(randomInt==0)
            {
                // PREVENT FOCUS - INSERT CODE HERE. (The line below is a failed attempt.)
                FocusManager.SetFocusedElement(this, myLabel);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

以下代码似乎可以解决问题:

// PREVENT FOCUS - INSERT CODE HERE.
myLabel.Focusable = true;
myLabel.Focus();
myLabel.Focusable = false;

我也更改了这行代码:

myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;

进入这个:

myTextbox.GotFocus += myTextbox_GotKeyboardFocus;

答案 1 :(得分:1)

我希望你知道你已经连接到键盘焦点(TAB键)。

void textBox1_GotFocus(object sender, System.EventArgs e)
{
    if (!this.checkBox1.Checked)
        this.checkBox1.Focus();

    else
        this.textBox1.Focus();

}