[英]WPF Editable ComboBox validation
我要完成的工作是能够验证在可编辑组合框中键入的新类别,或从现有组合框中的类别列表中选择的新类别。
验证仅适用于selectedItem,不适用于输入到Text中的新文本。 一旦将ValidateOnDataErrors="True"
添加到ComboBox的Text属性,输入新文本的事件就不会触发。 类别是具有ID和Name的简单对象。
XAML:
<Window.Resources>
<ControlTemplate x:Key="ValidationErrorTamplate">
<Border BorderBrush="DodgerBlue" BorderThickness="0.75">
<AdornedElementPlaceholder />
</Border>
</ControlTemplate>
<Style x:Key="ElementInError" TargetType="{x:Type FrameworkElement}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={x:Static RelativeSource.Self}}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<ComboBox Name="CbCategory"
DisplayMemberPath="Name"
IsEditable="True"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedCategory,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"
Style="{StaticResource ElementInError}"
Text="{Binding NewCategory.Name,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"
Validation.ErrorTemplate="{StaticResource ValidationErrorTamplate}" />
ViewModel:( : IDataErrorInfo
)
private Category _newCategory;
private Category _selectedCategory;
public ExpenseCategory SelectedCategory
{
get { return _selectedCategory; }
set
{
if (Equals(_selectedCategory, value)) return;
_selectedCategory = value;
SendPropertyChanged("SelectedCategory");
}
}
public ExpenseCategory NewExpenseCategory
{
get { return _newExpenseCategory ?? (_newExpenseCategory = new ExpenseCategory()); }
set
{
if (Equals(_newExpenseCategory, value)) return;
_newExpenseCategory = value;
SendPropertyChanged("NewExpenseCategory");
}
}
public string this[string propertyName]
{
get
{
switch (propertyName)
{
case "SelectedExpenseCategory":
case "NewExpenseCategory":
{
if ((SelectedCategory == null) || (NewCategory == null)
{
return "Category must be selected or entered";
}
}
break;
}
return string.Empty;
}
它能正常工作,这可能不是一流的方法,但可以完成工作。
基本上,我将NewCategory更改为字符串,而不是Category类型的对象。 当用户将新值填充到组合框中时,它将基于传递到NewCategory构造函数中的值来启动新的SelectedCategory。 如果我保留对象类型为类别的NewCategory,它将无法正常工作。
public string NewExpenseCategory
{
get { return _newExpenseCategory ?? (_newExpenseCategory = ""); }
set
{
if (Equals(_newExpenseCategory, value))
return;
_newExpenseCategory = value;
SendPropertyChanged("NewExpenseCategory");
SelectedExpenseCategory = new ExpenseCategory
{
Name = value
};
}
}
public string this[string propertyName]
{
get
{
switch (propertyName)
{
case "SelectedExpenseCategory":
case "NewExpenseCategory":
{
if ((SelectedExpenseCategory.Name.Length == 0) && (NewExpenseCategory.Length == 0))
{
return "Category must be selected or entered";
}
}
break;
}
return string.Empty;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.