使用 WPF 验证机制可以轻松完成此操作。首先,既然你想遵循 WPF 架构,我建议你使用 WPF命令模型 http://msdn.microsoft.com/es-es/library/ms752308%28VS.85%29.aspx.
现在要实现您的功能,您可以添加CommandBinding
到 Window/UserControl 或Button
itself:
<Button Content="Save" Command="Save">
<Button.CommandBindings>
<CommandBinding Command="Save"
Executed="Save_Executed" CanExecute="Save_CanExecute" />
</Button.CommandBindings>
</Button>
现在您可以订阅CanExecute
事件根据您的验证逻辑启用或禁用您的按钮。在继续之前,我建议您阅读以下内容:
Windows Presentation Foundation 中的验证 http://www.codeproject.com/KB/WPF/wpfvalidation.aspx
在 WPF 中使用自定义验证规则 http://www.developingfor.net/wpf/using-custom-validation-rules-in-wpf.html
满足您的要求的最简单方法如下:
XAML
<Window x:Class="GridScroll.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GridScroll"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<TextBlock Text="User Name" Grid.Column="0" Grid.Row="0"/>
<TextBox Grid.Column="1" Grid.Row="0" Text="{Binding Path=UserName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Text="Password" Grid.Column="0" Grid.Row="1"/>
<TextBox Grid.Column="1" Grid.Row="1" Text="{Binding Path=Password,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="Save" Grid.Row="2" Grid.ColumnSpan="2" Width="100" HorizontalAlignment="Right" Command="Save">
<Button.CommandBindings>
<CommandBinding Command="Save"
Executed="Save_Executed" CanExecute="Save_CanExecute"/>
</Button.CommandBindings>
</Button>
</Grid>
Code behind
public partial class Window1 : Window,INotifyPropertyChanged
{
public Window1()
{
InitializeComponent();
DataContext = this;
}
private string userName;
public string Username
{
get
{
return userName;
}
set
{
userName = value;
OnPropertyChanged("UserName");
}
}
private string password;
public string Password
{
get
{
return password;
}
set
{
password = value;
OnPropertyChanged("Password");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
private void Save_Executed(object sender, ExecutedRoutedEventArgs e)
{
//Your code
}
private void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = !(string.IsNullOrEmpty(Username) && string.IsNullOrEmpty(Password));
}
}
希望这可以帮助。