数据绑定似乎只适用于 MainWindow() WPF

Data binding only seems to work in MainWindow() WPF

我有点迷茫,我正在尝试将我的 GUI 上的标签绑定到我的代码中的字符串,但它似乎只有在我将代码放在我的 MainWindow() 块中并且我可以'不要从其他任何地方更新它。

这是我的 INotifyPropertyChanged class:

        public class MyClass : INotifyPropertyChanged
    {
        private string _testLabel;

        protected void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, e);
        }

        protected void OnPropertyChanged(string propertyName)
        {
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }

        public string testLabel
        {
            get { return _testLabel; }
            set
            {
                if (value != _testLabel)
                {
                    _testLabel = value;
                    OnPropertyChanged("testLabelChanged");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

这是 MainWindow() 块:

        public MainWindow()
    {
        InitializeComponent();
        testLabelName.DataContext = t;
        t.testLabel = "Hello World 32432";
    }

我也在外面声明过:

MyClass t = new MyClass();

这是我的 XAML:

的片段
<Label Name="testLabelName" Content="{Binding Path=testLabel, Mode=OneWay}" Height="28" Margin="0,0,12,29" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="128" />

我尝试通过使用按钮事件来设置标签来测试它,它似乎设置了但在 GUI 上没有任何变化。我在想 GUI 不会在 PropertyChanged 事件上更新。这样对吗?

谢谢,

请更改:

OnPropertyChanged("testLabelChanged");

至:

OnPropertyChanged("testLabel");

"anywhere else" 是什么意思?

我认为你的代码有一个小问题。当您触发 PropertyChanged 事件时,您需要指定 属性 的名称。 属性 的代码应如下所示:

    public string testLabel
    {
        get { return _testLabel; }
        set
        {
            if (value != _testLabel)
            {
                _testLabel = value;
                OnPropertyChanged("testLabel"); // not testLabelChanged
            }
        }
    }

除非您为 属性 指定正确的名称,否则 UWP 无法知道哪个 属性 已实际更改,因此不会更新 UI.