【问题标题】:Data binding only seems to work in MainWindow() WPF数据绑定似乎只适用于 MainWindow() WPF
【发布时间】:2016-05-11 11:12:25
【问题描述】:

我有点迷茫,我试图将我的 GUI 上的标签绑定到我的代码中的一个字符串,但它似乎只有在我将代码放在我的 MainWindow() 块中并且我无法更新时才有效它来自其他任何地方。

这是我的 INotifyPropertyChanged 类:

        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 的 sn-p:

<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 事件。是这样吗?

谢谢,

【问题讨论】:

    标签: c# wpf xaml binding propertychanged


    【解决方案1】:

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

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

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

    【讨论】:

    • 你先生,太棒了。谢谢!
    • 将来避免拼写错误的最简单方法是使用 C# 6 的 OnPropertyChanged(nameof(testLabel)) 功能。
    【解决方案2】:

    请更改:

    OnPropertyChanged("testLabelChanged");
    

    到:

    OnPropertyChanged("testLabel");
    

    【讨论】:

      【解决方案3】:

      “其他地方”是什么意思?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多