Bind IsEnabled property to Boolean in WPF
Asked Answered
L

1

5

I have a TextBox which needs to be enabled / disabled programmatically. I want to achieve this using a binding to a Boolean. Here is the TextBox XAML:

<TextBox Height="424" HorizontalAlignment="Left" 
                 Margin="179,57,0,0" Name="textBox2" 
                 VerticalAlignment="Top" Width="777"
                 TextWrapping="WrapWithOverflow" 
                 ScrollViewer.CanContentScroll="True" 
                 ScrollViewer.VerticalScrollBarVisibility="Auto" 
                 AcceptsReturn="True" AcceptsTab="True" 
                 Text="{Binding Path=Text, UpdateSourceTrigger=PropertyChanged}"
                 IsEnabled="{Binding Path=TextBoxEnabled}"/>

Notice the Text property is bound as well; it is fully functional, which makes me think it is not a DataContext issue.

However, when I call this code:

private Boolean _textbox_enabled;
public Boolean Textbox_Enabled
{
    get { return _textbox_enabled; }
    set
    {
        OnPropertyChanged("TextBoxEnabled");
    }
}

It does not work. To give further information, the TextBox_Enabled property is changed by this method:

public void DisabledTextBox()
{
     this.Textbox_Enabled = false;
}

..which is called when a key combination is pressed.

Lading answered 23/8, 2014 at 23:28 Comment(1)
@Stígandr has a correct answer, however I would like to note that best practice is to use nameof() when referencing literal names of code elements. For example, if your line had been OnPropertyChanged(nameof(TextboxEnabled)), the IDE would have pointed out the error for you, since no such property exists. And, when you use the Rename feature to change the property name, it would automatically update.Saucer
K
19

Here are your little typos!

    private Boolean _textbox_enabled;
    public Boolean TextboxEnabled // here, underscore typo
    {
        get { return _textbox_enabled; }
        set
        {
            _textbox_enabled = value; // You miss this line, could be ok to do an equality check here to. :)
            OnPropertyChanged("TextboxEnabled"); // 
        }
    }

Another thing for your xaml to update the text to the vm/datacontext

Text="{Binding Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding TextBoxEnabled}"/>
Kickapoo answered 23/8, 2014 at 23:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.