【问题标题】:How to checks that whether UserControl is Valid or not如何检查用户控件是否有效
【发布时间】:2011-03-02 00:35:55
【问题描述】:

我在用户控件中有一个实现 ValidationRule 的文本框,它工作正常,现在在我使用此控件的窗口中有一个按钮,如果用户控件中的文本框无效,我希望禁用该按钮

【问题讨论】:

    标签: .net wpf validation user-controls


    【解决方案1】:

    这里的技巧是使用命令,而不是点击事件。命令包含确定命令是否有效的逻辑,以及执行命令时要运行的实际代码。

    我们创建一个命令,并将按钮绑定到它。如果 Command.CanExecute() 返回 false,该按钮将自动禁用。使用命令框架有很多好处,但我不会在这里详细介绍。

    下面是一个可以帮助您入门的示例。 XAML:

    <StackPanel>
        <Button Content="OK" Command="{Binding Path=Cmd}">
        </Button>
        <TextBox Name="textBox1">
            <TextBox.Text>
                <Binding Path="MyVal" UpdateSourceTrigger="PropertyChanged" >
                    <Binding.ValidationRules>
                        <local:MyValidationRule/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
    </StackPanel>
    

    UserControl 代码隐藏(这可能与您已有的类似,但我已将其包含在内以显示命令的创建方式):

    public partial class UserControl1 : UserControl
    {
        private MyButtonCommand _cmd;
        public MyButtonCommand Cmd
        {
            get { return _cmd; }
        }
    
        private string _myVal;
        public string MyVal
        {
            get { return _myVal; }
            set { _myVal = value; }
        }
    
        public UserControl1()
        {
            InitializeComponent();
            _cmd = new MyButtonCommand(this);
            this.DataContext = this;
        }
    }
    

    命令类。这个类的目的是使用Validation系统来判断命令是否有效,并在TextBox.Text改变时刷新它的状态:

    public class MyButtonCommand : ICommand
    {
        public bool CanExecute(object parameter)
        {
            if (Validation.GetHasError(myUserControl.textBox1))
                return false;
            else
                return true;
        }
    
        public event EventHandler CanExecuteChanged;
        private UserControl1 myUserControl;
    
        public MyButtonCommand(UserControl1 myUserControl)
        {
            this.myUserControl = myUserControl;
            myUserControl.textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
        }
    
        void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (CanExecuteChanged != null)
                CanExecuteChanged(this, EventArgs.Empty);
        }
    
        public void Execute(object parameter)
        {
            MessageBox.Show("hello");
        }
    }
    

    【讨论】:

    • 感谢您的回答,但实际上我不需要用户控件内的按钮,无论如何我想出了一个解决方案,我在我的用户控件“IsValid”中添加了一个属性,并将其设置为 Validation.Error事件,我在托管窗口的按钮的 CanExecute 事件中使用了此属性。所以它工作正常。
    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2016-05-09
    • 1970-01-01
    相关资源
    最近更新 更多