【问题标题】:WPF Expander should expand when a member control gets focusWPF Expander 应在成员控件获得焦点时展开
【发布时间】:2018-08-09 05:10:32
【问题描述】:

我在扩展器中有两个文本框。单击按钮时,我正在验证文本框的文本值。如果文本框为空,则为文本框提供 foucs。

我想要实现的是,当这些 texbox 之一获得焦点时,扩展器会自动展开。

我在互联网上找不到任何方法。有可能吗?

xaml:

    <Grid>
        <Expander Header="Textbox Expander">
            <StackPanel Orientation="Vertical">
                <TextBox Name="txtName" Height="30" Width="100" Background="WhiteSmoke" />
                <TextBox Name="txtAge" Height="30" Width="100" Background="WhiteSmoke" />
            </StackPanel>
        </Expander>
        <Button Name="btnDone" Content="Done" Width="50" Height="50" Click="btnDone_Click"/>
    </Grid>

c#:

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

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

        private void btnDone_Click(object sender, RoutedEventArgs e)
        {
            Validation validation = new Validation();
            if(validation.validate(ref txtName) && validation.validate(ref txtAge))
            {
                //Do Something.
            }
        }
    }            
}

编辑:由于这个验证类在另一个应用程序中,我无法编辑它。

//Seperate class in another application which cannot be edited
public class Validation
{
    public bool validate(ref TextBox txtobj)
    {
        if (string.IsNullOrWhiteSpace(txtobj.Text))
        {
            MessageBox.Show("Please Enter Data..!");
            txtobj.Focus();
            return false;
        }
        return true;
    }
}

【问题讨论】:

    标签: c# wpf xaml expander


    【解决方案1】:

    您想要实现的目标实际上非常简单。 先给 Expander 起个名字

    <Expander x:Name="MyExpander" ... />
    

    其次,在您的验证中,在您关注文本框之前,只需展开扩展器

    MyExpander.IsExpanded = true;
    ...
    

    -- 编辑以满足新要求--

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void btnDone_Click(object sender, RoutedEventArgs e)
        {
            Validation validation = new Validation();
    
            // since you know that the text will be focused when the validation fails
            var result1 = validation.validate(ref txtName);
            var result2 = validation.validate(ref txtAge);
            MyExpander.IsExpanded = !result1 || !result2;
    
            if(result1 && result2)
            {
               //Do Something.
            }
        }
    }
    

    但我必须承认,这不是最好的解决方案。应该有一种更简单的方法可以直接将 Trigger 添加到 Expander Style。 (我会留给其他人,因为我没有更多的时间)

    【讨论】:

    • 感谢您的回答。对不起,我没有正确提及。我需要在 MainWindow 类本身中执行此操作。因为验证类在单独的应用程序之外,所以我无法对其进行任何更改。我将编辑问题。
    • @SajithSageer 我刚刚更新了答案。就像我最后说的,这只是一个解决方案,不是最好的。
    • 感谢您抽出宝贵时间回答。如果我有多个扩展器和相应的文本框,这种方法可能会有点棘手。如果我能找到任何其他解决方案,我一定会使用它。谢谢。
    猜你喜欢
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多