C# WPF 数据绑定标签内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17233651/
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-10 08:54:42  来源:igfitidea点击:

WPF Data binding Label content

c#wpfdata-bindinginotifypropertychanged

提问by HansElsen

I'm trying to create a simple WPF Application using data binding. The code seems fine, but my view is not updating when I'm updating my property. Here's my XAML:

我正在尝试使用数据绑定创建一个简单的 WPF 应用程序。代码看起来不错,但是当我更新我的属性时,我的视图没有更新。这是我的 XAML:

<Window x:Class="Calculator.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:calculator="clr-namespace:Calculator"
        Title="MainWindow" Height="350" Width="525"
        Name="MainWindowName">
    <Grid>
        <Label Name="MyLabel" Background="LightGray" FontSize="17pt" HorizontalContentAlignment="Right" Margin="10,10,10,0" VerticalAlignment="Top" Height="40" 
               Content="{Binding Path=CalculatorOutput, UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</Window>

Here's my code-behind:

这是我的代码隐藏:

namespace Calculator
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            DataContext = new CalculatorViewModel();
            InitializeComponent();
        }
    }
}

Here's my view-model

这是我的视图模型

namespace Calculator
{
    public class CalculatorViewModel : INotifyPropertyChanged
    {
        private String _calculatorOutput;
        private String CalculatorOutput
        {
            set
            {
                _calculatorOutput = value;
                NotifyPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            var handler = PropertyChanged;
            if (handler != null)
               handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

I'm can't see what I am missing here?? o.O

我看不到我在这里缺少什么??oO

采纳答案by HansElsen

CalculatorOutputhas no getter. How should the View get the value? The Property has to be public as well.

CalculatorOutput没有吸气剂。View应该如何获取值?该物业也必须是公开的。

public String CalculatorOutput
{
    get { return _calculatorOutput; }
    set
    {
        _calculatorOutput = value;
        NotifyPropertyChanged();
    }
}