Question

I have a WPF app where i want to control IsEnabled property of several textboxes in code by setting just one bool. So i decide to add databinding for textboxes IsEnabled property. Here is the source object definition:

<Window.Resources>
     <src:QuestionControlsState x:Key="QuestionContorlsState" IsEnabled="True"/>
</Window.Resources>

Where 'QuestionControlsState' simple class with only one public property 'IsEnabled' Then i bind some of textboxes:

<TextBox Name="textBoxQuestion" 
                IsEnabled="{Binding Path=IsEnabled, Source={StaticResource QuestionContorlsState}}">

At this point it works fine, when i change IsEnabled attribute in Window.Resources section databinding works. But i want to control it from code, so i get source object:

 QuestionControlsState _questionControlsState = (QuestionControlsState)this.FindResource("QuestionContorlsState");

And now when i try to set _questionControlsState.IsEnabled, textbox state not change and there is now warnings in output.

Was it helpful?

Solution

Without seeing your code, I'm guessing your QuestionControlsState class isn't implementing INotifyPropertyChanged.

Modify it like this:

public class QuestionControlsState : INotifyPropertyChanged
{
    private bool isEnabled = true;
    public bool IsEnabled
    {
        get { return isEnabled; }
        set
        {
            isEnabled = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("IsEnabled"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

This will trigger a PropertyChanged event whenever you change the IsEnabled property, notifying the view it needs to refresh.

Of course, if you're using the MVVM pattern, the correct way of doing this is binding all textboxes to a boolean IsEnabled property in the ViewModel and not by trying to find the static resource in codebehind... Then, a simple IsEnabled = false in the VM will disable all textboxes (without the need of a staticresource)

OTHER TIPS

Please use the MVVM pattern to passing data to tha XAML view and to encapsulate the view logic and to make the view logic testable.

With MVVM its very easy to create a observable property which can be bound to the IsEnabled properties of your controls. You only have to change the Property with a Command to true or false to enable or disable the property.

Thank you guys, Blachshma you was right i forgot to implement INotifyPropertyChanged interface on my custom class and now it works like it should. Thank you! I think about MVVM pattern and it looks cool but i just started with WPF and want to learn basics.

You can try to change StaticResource to DynamicResource.

You can find information here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top