WPF Data Binding to a string property

陌路散爱 提交于 2019-12-24 08:17:45

问题


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.


回答1:


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}" />



回答2:


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

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


来源:https://stackoverflow.com/questions/724763/wpf-data-binding-to-a-string-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!