Search code examples
c#wpfxamluser-controlsuniversal

PropertyChanged not updating UI in user control - universal app


In my app I have a user control with the following XAML segment

<StackPanel x:Name="stackPanel" Style="{StaticResource sPanel1}" >
    <ToggleButton Style="{StaticResource tButton}">
        <TextBlock Text="{Binding Note, Mode=TwoWay}" Style="{StaticResource textBlockStyle}"/>
    </ToggleButton>
</StackPanel>

that 'Note' bound in the TextBlock is defined in my model as so:

private string m_Note;
public string Note
{
    get { return m_Note; }
    set
    {
        m_Note = value;
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("m_Note"));
    }
}

The 'Note' property updates when an event handler from my user control code-behind fires the event:

public void cBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    cm.Note = cBox.SelectedItem.ToString();
}

But every time I select an item from the ComboBox the UI does not update. I know that the binding is correct because when I initialize 'Note' in the model's constructor it does show it's value in the UI, and I know that 'Note' gets the cBox.SelectedItem value because I've walked through the code. What am I missing?


Solution

  • The binding path and mode in the View is correct. That is why you get the value on initialize. Your bound property however is not raising the correct Property Name on property changed. The UI is listening for Note but you are raising m_Note.

    You need to update to

    private string m_Note;
    public string Note
    {
        get { return m_Note; }
        set
        {
            m_Note = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Note"));
        }
    }