0
我有一個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);
}
}
}
}
的GotKeyboardFocus事件當您單擊文本框時也會觸發。 – user181813
我試圖將你的想法整合到我的示例代碼中(通過調用myLabel.Focus()),並且不幸的是它似乎無法工作。 – user181813