WPF Data binding Label content

帅比萌擦擦* 提交于 2019-12-01 14:00:49

问题


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:

<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


回答1:


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

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


来源:https://stackoverflow.com/questions/17233651/wpf-data-binding-label-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!