我有3个文本框。我怎么知道他们中哪一个有焦点?
if (TextBoxExtendedSearchName.Focus() == false &&
TextBoxExtendedSearchNomenclature.Focus() == false
&& TextBoxExtendedSearchSpecialist.Focus() == false)
{
window.Close();
}
这不起作用
我使用WPF
private void TextBox1_LostFocus(object sender, RoutedEventArgs e)
{
if (!TextBox1.IsFocused && !TextBox2.IsFocused)
MessageBox.Show("Not Focus");
}
private void TextBox2_LostFocus(object sender, RoutedEventArgs e)
{
if (!TextBox1.IsFocused && !TextBox2.IsFocused)
MessageBox.Show("Not Focus");
}
此示例不起作用
我想我明白了问题所在。当我在“迷失焦点”事件中这样做时,它不起作用。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TextBox1_LostFocus(object sender, RoutedEventArgs e)
{
if (!TextBox1.IsFocused && !TextBox2.IsFocused)
MessageBox.Show("Not Focus");
else
MessageBox.Show("Yes Focus");
}
private void TextBox2_LostFocus(object sender, RoutedEventArgs e)
{
if (!TextBox1.IsFocused && !TextBox2.IsFocused)
MessageBox.Show("Not Focus");
else
MessageBox.Show("Yes Focus");
}
XAML
<Window x:Class="TrainWPF.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>
<TextBox x:Name="TextBox1" HorizontalAlignment="Left" Height="25" Margin="62,61,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="205" LostFocus="TextBox1_LostFocus"/>
<TextBox x:Name="TextBox2" HorizontalAlignment="Left" Height="23" Margin="62,145,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="205" LostFocus="TextBox2_LostFocus"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="267,249,0,0" VerticalAlignment="Top" Width="96" RenderTransformOrigin="0.5,0.5" Height="37">
<Button.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="0.397"/>
<TranslateTransform/>
</TransformGroup>
</Button.RenderTransform>
</Button>
</Grid>
</Window>
这不起作用
我理解这是我的逻辑错误
答案 0 :(得分:1)
试试这个:
//Logical focus
var focusedControl = FocusManager.GetFocusedElement(this);
//KeyBoard focus
var focusedControl = Keyboard.FocusedElement;
// dummy logic to close the window when all the three textboxes are not focused.
List<TextBox> items=new List<TextBox>();
items.Add(TextBoxExtendedSearchName);
items.Add(TextBoxExtendedSearchNomenclature);
items.Add(TextBoxExtendedSearchSpecialist);
if(!items.Any(o=>o==focusedControl))
{
window.Close();
}
答案 1 :(得分:0)
您使用的功能错误。您需要使用IsFocused
属性来获取Control
有焦点。
请参阅此处的文档:Link
使用您的代码:
if (!TextBoxExtendedSearchName.IsFocused
&& !TextBoxExtendedSearchNomenclature.IsFocused
&& !TextBoxExtendedSearchSpecialist.IsFocused)
{
window.Close();
}
如果窗口中没有Close
,则会Focus
。