James
James

Reputation: 3625

WPF Data Binding to a string property

I have a question about data binding which I am struggling with.

I have the following property in my xaml.cs file:

    private string _stationIdInstruction;

    public event PropertyChangedEventHandler PropertyChanged;

    public string StationIdInstruction
    {
        get { return _stationIdInstruction; }
        set
        {
            _stationIdInstruction = value;
            OnPropertyChanged("StationIdInstruction");
        }
    }

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

How can I bind a TextBlock to StationIdInstructions so it picks up the string property as its Text and update the TextBlock.Text when I update StationIdInstructions.

Any help is appreciated.

Upvotes: 2

Views: 22818

Answers (2)

Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

Yes, and don't forget to specify the binding context. E.g.,

<Window ... Name="MyWindow">
  <Grid DataContext="{Binding ElementName=MyWindow, Path=.}">
    <TextBlock Text="{Binding Path=StationIdInstruction}" />

Upvotes: 4

Arcturus
Arcturus

Reputation: 27055

Set your StationIdInstructions object on the DataContext of your control, and your TextBlock like so:

<TextBlock Text="{Binding StationIdInstruction}" />

Upvotes: -1

Related Questions