Question

Quick googling doesn't yield a viable duplicate for this. I have what I hope is a pretty simple question about WPF error templates and/or the UpdateSourceTrigger property of a Binding. I'm kind of a WPF n00b so bear with me.

I can't post code per se (work-related), but here's the basic idea:

I have a standard set of a couple radio buttons in the same group. I have a text box "attached" to one of them, in the sense that TextBox.isEnabled is databound to rb.isChecked of one of the radio buttons.

The text box validates on data error, using PropertyChanged triggers. When an error occurs, it draws a red box around itself.

The problem I'm having is that "empty text box" is an error condition if and only if the radio button has enabled the text box. I need the error box to go away when I select the other radio button, but it doesn't.

My first thought was to try to tie something in the error template to (HasError && IsEnabled) but I can't see a clear way to do that.

I think that maybe triggering the TextBox (via UpdateSourceTrigger) on the FocusLost event in addition to PropertyChanged might work. Is there a way to do that?

Alternate solutions are welcome, of course.

Was it helpful?

Solution

Validation will re-run whenever PropertyChanged is called. This means that you can force revalidation by raising the PropertyChanged event for the TextBox binding.

Since you need to revalidate when the RadioButton.IsChecked changes you can raise PropertyChanged for the property that the TextBox is bound to on the setter for the property that the RadioButton is bound to.

Example:

class MyViewModel
{
    public bool MyRadioButtonIsSelected
    {
       get { return myRadioButtonIsSelectedBacking; }
       set
       {
           myRadioButtonIsSelectedBacking= value;
           OnPropertyChanged("MyRadioButtonIsSelected");

           // Force revalidation of MyTextBoxValue
           OnPropertyChanged("MyTextBoxValue");
       }
    }

    public string MyTextBoxValue
    {
       get { return myTextBoxPropertyBackingField; }
       set
       {
           myTextBoxPropertyBackingField= value;
           OnPropertyChanged("MyTextBoxValue");
       }
    }
}

Xaml:

<RadioButton
    Content="My Radio Button"
    IsChecked="{Binding MyRadioButtonIsSelected}" />
<TextBox 
    IsEnabled="{Binding MyRadioButtonIsSelected}"
    Text="{Binding MyTextBoxValue, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top