简体   繁体   中英

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.

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

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

在控件的DataContext上设置StationIdInstructions对象,并像这样设置TextBlock:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM