I have a textbox inside usercontrol that implements ValidationRule and it is working fine, now in the window where i'm using this control has one button, and i want that button to be disabled if text开发者_开发技巧box inside usercontrol is not valid
The trick here is to use a Command, instead of the click event. A command contains logic to determine whether the command is valid, as well as the actual code to run when the command is executed.
We create a command, and bind the button to it. The button will automatically become disabled if Command.CanExecute() returns false. There are a bunch of benefits to using the command framework, but I won't go into those here.
Below is an example which should get you started. The 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>
The UserControl code-behind (this is probably similar to what you already have, but I've included it to show how the command is created):
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;
}
}
The Command class. The purpose of this class is to decide whether the command is valid using the Validation system, and to refresh it's state when the TextBox.Text changes:
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");
}
}
精彩评论