WPF阻止条件下组合框选择的更改



我有一个ComboBox,它的选定索引被绑定到一个整数中。如果不满足某个条件,我要做的是防止组合框选择发生更改。以下是我目前拥有的

在xaml中:

<ComboBox SelectedIndex="{Binding CurrentMinCondition,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
<ComboBoxItem>NA</ComboBoxItem>
<ComboBoxItem>LT</ComboBoxItem>
<ComboBoxItem>GT</ComboBoxItem>
</ComboBox>

在cs:中

private int _currentMinCondition = 0;
public int CurrentMinCondition
{
get { return _currentMinCondition; }
set
{
if (/*Condition is met*/){
_currentMinCondition = value;
OnPropertyChanged("CurrentMinCondition");
}
else
{
MessageBox.Show("Error");
_currentMinCondition = 0;
OnPropertyChanged("CurrentMinCondition");
}
}
}

现在我认为这会起作用,但实际情况是,当我更改组合框中的选择,但条件不满足时,我的MessageBox显示错误,但图形组合框会更改其选择。我该如何防止这种情况发生?

您可以使用错误验证。在结果不是预期的情况下,您可以返回错误的验证结果:

<ComboBox SelectedIndex="{Binding CurrentMinCondition,Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged, 
ValidateOnDataErrors=True, 
NotifyOnValidationError=True,
ValidatesOnExceptions=True}",
Validation.Error="MethodToValidate">
<ComboBoxItem>NA</ComboBoxItem>
<ComboBoxItem>LT</ComboBoxItem>
<ComboBoxItem>GT</ComboBoxItem>
</ComboBox>

在属性中,您应该抛出异常:

public int CurrentMinCondition
{
get {return _currentMinCondition;}
set 
{
if(value != _currentMinCondition)
{
if(condition met)
throw new Exception("Message error");
else
{
_currentMinCondition = value;
PropertyChanged("CurrentMinCondition");
}
}
}
}

然后在您的验证方法中:

private void ValidateMethod(object sender, ValidationErrorEventArgs e)
{
e.Handled = true;
}

这将用一个错误矩形标记组合框,如果出现错误,则基本值将不会更改。

最新更新