BpH
BpH

Reputation: 41

WPF data binding not working after Initialize

I'm having some problems with data binding. It seems that values update up until the point when the form displays, after which it has no interest in updating.

On my view I have a label.

<Label  Background="{Binding info_bg}" Foreground="{Binding info_fg}" Margin="5" Grid.Row="0" FontFamily="Arial Rounded MT Bold" FontSize="24" Grid.Column="0" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" >
    <Label.Content>
        <AccessText TextWrapping="Wrap" Text="{Binding info}" TextAlignment="Center" VerticalAlignment="Center" />
    </Label.Content>
</Label>

In the code behind

public Client()
{
    _cvm = new ClientViewModel();
    this.DataContext = _cvm;

    InitializeComponent();

}

In the ClientViewModel class (extends a CommonBase class which has the INotifyPropertyChanged)

public class ClientViewModel : CommonBase
{

    private string _info = "";
    public string info
    {
        get
        {
            return _info;
        }
        set
        {
            _info = value;
            NotifyPropertyChanged("info");
        }
    }

    public ClientViewModel()
    {
        this._info = "TEST UPDATE";
    }

When I run this, the label shows TEST UPDATE as expected. In my code behind, I created a Window_KeyUp event to push the keys pressed through to the ClientViewModel class by calling _cvm.ProcessKey(e.Key);

public void ProcessKey(string key)
{
    this._info = key; 
}

MessageBox.Show(Info); gives me the key I pushed, so I know it's getting through, but the View isn't updating.

CommonBase class in case I've messed up here.

public class CommonBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string propertyName)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Thank you.

Upvotes: 0

Views: 988

Answers (1)

Emond
Emond

Reputation: 50692

Do not set the field like this this._info = key;

Instead set the property this.info = key;

This will invoke the set of the property and the PropertyChanged event will be raised. That is what is being observed by the view so it will respond.

(And while you are at it, start the properties with an uppercase.)

Upvotes: 2

Related Questions