WPF数据绑定到字符串属性

时间:2009-04-07 09:10:53

标签: c# wpf binding

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

我的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));
        }
    }

如何将TextBlock绑定到StationIdInstructions,以便它将字符串属性作为Text接收,并在更新StationIdInstructions时更新TextBlock.Text。

感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

是的,不要忘记指定绑定上下文。如,

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

答案 1 :(得分:-1)

在您的控件的DataContext上设置您的StationIdInstructions对象,并将TextBlock设置为:

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