2

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
James
  • 3,597
  • 11
  • 47
  • 57
  • Your source code has a small error: either you forgot an opening "{" after "if (PropertyChanged != null)", or you're closing a non-existing if-block. – vstrien Apr 14 '11 at 13:29

2 Answers2

4

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}" />
Dmitri Nesteruk
  • 23,067
  • 22
  • 97
  • 166
-1

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

<TextBlock Text="{Binding StationIdInstruction}" />
Arcturus
  • 26,677
  • 10
  • 92
  • 107