WPF Data binding Label content

HansElsen picture HansElsen · Jun 21, 2013 · Viewed 79k times · Source

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

Answer

user1522991 picture user1522991 · Jun 21, 2013

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();
    }
}