C# WPF 数据绑定到字符串属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/724763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:36:14  来源:igfitidea点击:

WPF Data Binding to a string property

c#wpfbinding

提问by James

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

我有一个关于数据绑定的问题,我正在努力解决这个问题。

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

我的 xaml.cs 文件中有以下属性:

    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.

如何将 TextBlock 绑定到 StationIdInstructions,以便它在我更新 StationIdInstructions 时选择字符串属性作为其文本并更新 TextBlock.Text。

Any help is appreciated.

任何帮助表示赞赏。

采纳答案by Dmitri Nesteruk

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

回答by Arcturus

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

在控件的 DataContext 和 TextBlock 上设置 StationIdInstructions 对象,如下所示:

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