WPF Data Binding : enable/disable a control based on content of var?

Do you have a ViewModel holding your string property set as the DataContext of the View where you try to do this Binding?

Then the following will work:

  // Example ViewModel
public class MyClass : INotifyPropertyChanged
{
    private string text;

    public string Text
    {
        get { return text; }
        set 
        { 
            text = value;
            UpdateProperty("Text");
            UpdateProperty("HasContent");
        }
    }

    public bool HasContent
    {
        get { return !string.IsNullOrEmpty(text); }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    protected void UpdateProperty(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

Then you should have done something like this in the code behind of the view:

this.DataContext = new MyClass();

And a Xaml example:

 <StackPanel>
        <TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
        <Button IsEnabled="{Binding HasContent}">
            Click Me!
        </Button>
    </StackPanel>

Since you're probably looking to bind the IsEnabled property of the button based on a string, try making a converter for it.

Ie...


<StackPanel>
<StackPanel.Resources>
<local:SomeStringConverter mystringtoboolconverter />
</StackPanel.Resources>
<Button IsEnabled="{Binding ElementName=mytree, Path=SelectedItem.Header, Converter={StaticResource mystringtoboolconverter}}" />
<StackPanel>

and the converter:


[ValueConversion(typeof(string), typeof(bool))]
    class SomeStringConverter : IValueConverter {
        public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) {
            string myheader = (string)value;
            if(myhead == "something"){
                return true;
            } else {
                return false;
            }
        }

        public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) {
            return null;
        }
    }

EDIT: Since the OP wanted to bind to a variable, something like this needs to be done:


public class SomeClass : INotifyPropertyChanged {
  private string _somestring;

  public string SomeString{
    get{return _somestring;}
    set{ _somestring = value; OnPropertyChanged("SomeString");}
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

}

Then, change the above binding expression to:

{Binding Path=SomeString, Converter={StaticResource mystringtoboolconverter}}

Note, you MUST implement INotifyPropertyChanged for your UI to be updated.