1
我有一个在usercontrol内实现ValidationRule的文本框,它工作正常,现在在我正在使用此控件的窗口中有一个按钮,我希望该按钮是禁用如果usercontrol内的文本框无效如何检查UserControl是否有效
我有一个在usercontrol内实现ValidationRule的文本框,它工作正常,现在在我正在使用此控件的窗口中有一个按钮,我希望该按钮是禁用如果usercontrol内的文本框无效如何检查UserControl是否有效
这里的技巧是使用命令,而不是点击事件。一个命令包含确定命令是否有效的逻辑以及执行该命令时要运行的实际代码。
我们创建一个命令,并将按钮绑定到它。如果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>
的用户控件代码隐藏(这可能是类似于您已经有了,但我将它来说明如何创建命令):
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;
}
}
的命令类。这个类的目的是决定命令是否有效使用验证系统,并刷新它的状态时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事件按钮中使用了此属性。所以它工作正常。 – Ali