开发者

Dynamically preventing a TextBox from getting focus

开发者 https://www.devze.com 2023-04-10 21:07 出处:网络
I have a System.Windows.Controls.TextBox which I would like to behave as follows: When you click it, it is determined dynamically if the TextBox gets focus or not. Here\'s a toy application which cont

I have a System.Windows.Controls.TextBox which I would like to behave as follows: When you click it, it is determined dynamically if the TextBox gets focus or not. Here's a toy application which contains a failed attempt at accomplishing this:

<!-- MainWindow.xaml -->
<Window x:Class="Focus.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.micr开发者_运维百科osoft.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);
            }
        }
    }
}


The following code seems to do the trick:

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

I also changed this line of code:

myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;

into this:

myTextbox.GotFocus += myTextbox_GotKeyboardFocus;


I hope you know that you hooked up to the keyboard focus (TAB key).

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

    else
        this.textBox1.Focus();

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号