Sinmson
Sinmson

Reputation: 237

Bind label Content to string property

I want to bind the content of a label to a local property called "Status".

Codesnipped:

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        var logFilePath = GetPathToAppDirPlusLocalPath("LogFiles/MainLog.txt");
        MainLog = new Log(@logFilePath);
        MainLog.Add("MainWindow initialized");
        this.DataContext = this;
    }

    private string _Status = null;
    public string Status
    {
        get
        {
            return _Status;
        }
        set
        {
            _Status = value;
            NotifyPropertyChanged("Status");  //Call the method to set off the PropertyChanged event.
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void NotifyPropertyChanged(string propertyName = "")
    {
        var handler = PropertyChanged;
        if (handler != null) 
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

XAML:

<Border x:Name="brd_Status" Grid.Row="9" Grid.ColumnSpan="10"
        HorizontalAlignment="Stretch" VerticalAlignment="Bottom"
        Background="Black" DataContext="Status">
        <Label x:Name="lbl_Status" Content="{Binding Path=Status,UpdateSourceTrigger=PropertyChanged}"
            Grid.Row="9" Grid.ColumnSpan="10"
            HorizontalAlignment="Center" VerticalAlignment="Bottom"
            FontSize="16" Foreground="White" FontFamily="Asenine">
        </Label>
    </Border>

I also tried Content = {Binding Status...} but makes no difference.

The label is just "null", while the property "Status" is "abcd1234...".

I debugged it and but, I am not sure where to search for a failure...

Upvotes: 0

Views: 1561

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61379

The issue is that MainWindow is not implementing INotifyPropertyChanged so even though you have and are raising the appropriate event, the runtime hasn't registered for it.

Change your class definition to:

public partial class MainWindow : Window, INotifyPropertyChanged

Also consider using a proper view model (look up MVVM), puting INPC on a view object is very bad design, and note that an UpdateSourceTrigger on a Label is useless as Label controls cannot be changed in the UI.

Upvotes: 1

Related Questions