【问题标题】:WPF Data Binding to a string propertyWPF 数据绑定到字符串属性
【发布时间】:2009-04-07 09:10:52
【问题描述】:

我有一个关于数据绑定的问题。

我的 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,以便它在我更新 StationIdInstructions 时将字符串属性作为其 Text 并更新 TextBlock.Text。

感谢任何帮助。

【问题讨论】:

  • 您的源代码有一个小错误:您在“if (PropertyChanged != null)”之后忘记了开头的“{”,或者您正在关闭一个不存在的 if 块。跨度>

标签: c# wpf binding


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 不起作用。错误说缺少依赖属性。
    猜你喜欢
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 2013-09-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多