1

我正在开发一个表格,其中一个要求是在前两个完成之前禁用大部分字段。为了可用性起见,我希望它设置好,以便在您从第二个字段 (Field_Two.LostFocus) 中跳出后,其余字段将被启用、显示,并且这些字段中的第一个被聚焦。我目前拥有的代码在启动时将所有字段的可见性设置为 visibility.hidden。它目前所做的是关注 Field_One (在启用字段的选项卡顺序中的下一个),但我已经确认条件已正确满足并且执行继续通过 return 语句。

Field.beenFocused 是我创建的一个变量,它被初始化为 false,然后在 Field 第一次获得焦点时设置为 true,我的 Field 类扩展了 TextBox;我所有的控件保存 Field_One 和 Field_Two 都在 Stackpanels 中。

C#

        void Field_Two_LostFocus(object sender, RoutedEventArgs e)
    {
        if (!Field_Three.beenFocused)
        {

            if (String.IsNullOrWhiteSpace(Field_One.Text) || String.IsNullOrWhiteSpace(Field_Two.Text))
                return;

            foreach (object u in ApplicationGrid.Children)
                if (u.GetType() == typeof(StackPanel))
                        ((StackPanel)u).IsEnabled = true;

            do { Field_Three.Focus(); }
            while (!Field_Three.beenFocused);
        }
    }
4

1 回答 1

0

You could try enabling/disabling in a TextChanged event, rather than a LostFocus event.

Here's some sample code.

MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <TextBox Name="textBox1" TextChanged="ValidateInitialFieldsOnChange"
                 Height="23" Width="120" />
        <TextBox Name="textBox2" TextChanged="ValidateInitialFieldsOnChange"
                 Height="23" Width="120" />
        <TextBox Name="textBox3" IsEnabled="False" Height="23" Width="120" />
    </StackPanel>
</Window>

MainWindow.xaml.cs:

using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ValidateInitialFieldsOnChange(object sender,
            TextChangedEventArgs e)
        {
            textBox3.IsEnabled = !string.IsNullOrWhiteSpace(textBox1.Text)
                && !string.IsNullOrWhiteSpace(textBox2.Text)
                ;
        }
    }
}

It would be fairly trivial to adapt this code to suit your scenario, and wouldn't require manually setting focus. You could probably rely on tab order instead.

But if tab order doesn't help, you can still use a combination of these approaches to solve the problem. Set focus in the LostFocus event, and enable in teh TextChanged event.

于 2011-07-10T21:39:14.073 回答