禁用IDataErrorInfo中的按钮验证
问题描述:
我在我的视图模型上有两个命令,在我的View上有两个按钮“Search”和“Clear”。我在我的ViewModel上实现了IDataErrorInfo并验证了输入字段。我如何禁用“清除”按钮的验证?禁用IDataErrorInfo中的按钮验证
<TextBox Text="{Binding SearchText, Mode=TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=True, ValidatesOnExceptions=True}"
Validation.ErrorTemplate="{StaticResource ErrorTemplate}"/>
<Button Content="Search" Command="{Binding SearchCommand}" />
<Button Content="Clear" Command="{Binding ClearCommand}" />
答
我假设您想要启用/禁用基于搜索文本框中的验证的清除按钮。我已经使用MvvmLight继电器命令来使用命名空间使用GalaSoft.MvvmLight.CommandWpf命令从最新的MVVMLight;请参阅下面的代码。
<Window x:Class="DataTemplateSelector_Learning.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window3" Height="300" Width="300">
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Search Text"/>
<TextBox Width="100" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,
ValidatesOnDataErrors=True, NotifyOnValidationError=True, ValidatesOnExceptions=True}" />
</StackPanel>
<Button Content="Search" Command="{Binding SearchCommand}" />
<Button Content="Clear" Command="{Binding ClearCommand}" />
</StackPanel>
</Grid>
public partial class Window3 : Window
{
public Window3()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
class ViewModel:INotifyPropertyChanged,IDataErrorInfo
{
private string searchText;
private bool enableClear;
public string SearchText
{
get { return searchText; }
set { searchText = value; Notify("SearchText"); }
}
public ICommand SearchCommand { get; set; }
public ICommand ClearCommand { get; set; }
public ViewModel()
{
ClearCommand = new RelayCommand(OnClear, CanClear);
}
private bool CanClear()
{
return enableClear;
}
private void OnClear()
{
}
public event PropertyChangedEventHandler PropertyChanged;
private void Notify(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
public string Error
{
get { return String.Empty; }
}
public string this[string columnName]
{
get
{
String errorMessage = String.Empty;
if (!string.IsNullOrEmpty(SearchText))
{
if (SearchText.Length > 0)
{
enableClear = true;
}
else
{
enableClear = false;
}
}
return errorMessage;
}
}
}
你的要求不是更清晰。您是否希望根据Seach文本框中的文本禁用清除按钮。示例如果seach不为空或为空,请启用清除按钮。请解释 – 2015-02-08 22:04:25