开发者

Silverlight: Two-Way binding on ComboBox doesn't hit BindingValidationError handler with null

I've scoured the internet and have yet to find a solution. Help me Stack-Overflow-Kenobi, you're my only hope!

So I've got this Silverlight application, right? And I have a combobox that's bound to a non-nullable database field so that it is populated on initialization with all possible values. And it's working fine in that regard.

However, when I SubmitChanges without having selected an item, no valida开发者_如何学JAVAtion error is thrown, so my BindingValidationError handler is never activated. Now I would expect (and kinda need) an error to be thrown when pushing null into a non-nullable database column. That way the user knows to select an item.

When the value is not null, it is pushed to the database just fine. Basically, the binding works fine: I just need to know why the BindingValidationError handler is not hit. ToggleError needs to be run if no item is selected.

foo()
{
    Binding databinding = new Binding(this.Id);

    databinding.Source = bindingObject;
    databinding.BindsDirectlyToSource = true;
    databinding.Mode = BindingMode.TwoWay;
    databinding.ValidatesOnDataErrors = true;
    databinding.ValidatesOnExceptions = true;
    databinding.ValidatesOnNotifyDataErrors = true;
    databinding.NotifyOnValidationError = true;
    databinding.UpdateSourceTrigger = UpdateSourceTrigger.Default;

    CmbBox.DisplayMemberPath = _DisplayMemberPath;
    CmbBox.SelectedValuePath = _SelectedValuePath;
    CmbBox.SetBinding(ComboBox.SelectedItemProperty, databinding);
    CmbBox.BindingValidationError +=  (sender, e) => ToggleError(e.Action == ValidationErrorEventAction.Added ? true : false , e.Error.ErrorContent.ToString());
}

private void ToggleError(bool enableError, string errorMessage)
{
    hasError = enableError;
    if (hasError)
    {
        CmbBox.Foreground = new SolidColorBrush(Utilities.DarkRed);
        Error.Visibility = Visibility.Visible;
        this.errorMessage = errorMessage;
    }
    else
    {
        CmbBox.Foreground = new SolidColorBrush(Utilities.DarkGreen);
        Error.Visibility = Visibility.Collapsed;
        errorMessage = null;
    }
}

Thank in advance : )

Cameron


The BindingValidationError event fires when a TwoWay Binding is updated and the setter throws an exception. If you never select a value for the ComboBox then the Binding is never updated and it will never throw an error. You need to do validation yourself before you call SubmitChanges.

If you are using Silverlight 4 you may want to look into using INotifyDataErrorInfo to do validation in your code and then update the UI to show the validation error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜