C# 文本框的wpf LostFocus事件
这是我的xaml结构C# 文本框的wpf LostFocus事件,c#,wpf,xaml,C#,Wpf,Xaml,这是我的xaml结构 <StackPanel> <m:TextBoxWithEllipsis IsEllipsisEnabled="True" Name="A" LostFocus="text_LostFocus"/> <m:TextBoxWithEllipsis IsEllipsisEnabled="True" Name="B" LostFocus="text_LostFocus"/> </StackPa
<StackPanel>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="A"
LostFocus="text_LostFocus"/>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="B"
LostFocus="text_LostFocus"/>
</StackPanel>
问题:如果有>=2个文本框,则其值为空(“”)
text\u LostFocus
以解决问题??
默认值:
- 这些文本框的值始终为空(默认值)
- 必须使用BeginInvoke=>因为我希望当用户单击文本框时,用户必须至少输入一个字符
<StackPanel>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="A"
LostFocus="text_LostFocus"/>
<TextBlock Name="AWarning" Foreground="Red" />
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="B"
LostFocus="text_LostFocus"/>
<TextBlock Name="BWarning" Foreground="Red" />
</StackPanel>
如果我是你,我就不会使用留言箱。 WPF有一个非常好的“绑定验证框架”(请看一个非常好的教程)。 否则,我会在每个文本框附近创建一个“警告”标签:
<StackPanel>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="A"
LostFocus="text_LostFocus"/>
<TextBlock Name="AWarning" Foreground="Red" />
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="B"
LostFocus="text_LostFocus"/>
<TextBlock Name="BWarning" Foreground="Red" />
</StackPanel>
有趣的实现XD当你有两个文本框时,想想发生了什么:1。输入第一个tb 2。您不需要输入任何内容,只需单击第二个3。tb1的lostfocus事件触发并打开一个对话框,再次关注tb1 4。因为tb1获得了焦点,所以tb2的lostfocus事件触发,它也会这样做,将焦点返回到tb2,并在无限循环中继续进行。而且-无需
BeginInvoke
。您已经在UI线程上。我认为这是WPF而不是WinForms,这System.Windows.Forms.DialogResult
可以很容易地替换为System.Windows.MessageBox
!我建议不要在有人没有输入数据就离开文本框时显示弹出窗口:这真的很烦人。目视标记(例如,旁边有一个红十字);在满足最低要求之前,也不要启用“提交”按钮。@GSPBeginInvoke
不会按您所说的做,它只是在特定的调度程序上运行代码<代码>textbox.Dispatcher.BeginInvoke((操作)(()=>{textbox.Focus();}))应替换为textbox.Focus()代码>有趣的实现XD当您有两个文本框时,想想发生了什么:1。输入第一个tb 2。您不需要输入任何内容,只需单击第二个3。tb1的lostfocus事件触发并打开一个对话框,再次关注tb1 4。因为tb1获得了焦点,所以tb2的lostfocus事件触发,它也会这样做,将焦点返回到tb2,并在无限循环中继续进行。而且-无需BeginInvoke
。您已经在UI线程上。我认为这是WPF而不是WinForms,这System.Windows.Forms.DialogResult
可以很容易地替换为System.Windows.MessageBox
!我建议不要在有人没有输入数据就离开文本框时显示弹出窗口:这真的很烦人。目视标记(例如,旁边有一个红十字);在满足最低要求之前,也不要启用“提交”按钮。@GSPBeginInvoke
不会按您所说的做,它只是在特定的调度程序上运行代码<代码>textbox.Dispatcher.BeginInvoke((操作)(()=>{textbox.Focus();}))
应替换为textbox.Focus()代码>
<StackPanel>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="A"
LostFocus="text_LostFocus"/>
<TextBlock Name="AWarning" Foreground="Red" />
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="B"
LostFocus="text_LostFocus"/>
<TextBlock Name="BWarning" Foreground="Red" />
</StackPanel>
private void text_LostFocus(object sender, RoutedEventArgs e)
{
TextBox textBox = ((TextBox)sender);
TextBlock textBlock = FindName(String.Concat(textBox.Name, "Warning")) as TextBlock;
textBlock.Text = String.IsNullOrWhiteSpace(textBox.Text) ? "Empty string!" : String.Empty;
}