How to use INotifyPropertyChanged correctly in WPF/XAML

强颜欢笑 提交于 2019-12-01 11:47:12

Works on my machine. Although, the cache is kind of wacky. I'd either create static readonly versions per type or forget about caching until required (premature optimization and all).

I created a sample project. The main window looks like this:

<Window x:Class="INPCTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:this="clr-namespace:INPCTest"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <this:MyObject />
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBlock
            Text="{Binding MyOutProperty}" />
        <TextBox
            Grid.Row="1"
            Text="{Binding MyInProperty, UpdateSourceTrigger=PropertyChanged}" />
    </Grid>
</Window>

I'm binding to an instance of MyObject, which I create in the xaml (you can do this in the codebehind if this isn't a familiar thing to you).

Here's the code for MyObject:

class MyObject : BindableObject
{
    private string _in;
    private string _out;
    public string MyOutProperty
    {
        get { return _out; }
        set { _out = value; this.RaisePropertyChanged("MyOutProperty"); }
    }
    public string MyInProperty
    {
        get { return _in; }
        set
        {
            _in = value;
            MyOutProperty = "The textbox below says: \"" + value + "\"";
            this.RaisePropertyChanged("MyInProperty");
        }
    }
}

How it all works together is:

  1. Window is created
  2. Instance of MyObject is instantiated and set to Window.DataContext
  3. TextBlock is bound to MyOutProperty
  4. TextBox is bound to MyInProperty
  5. User types 'X' in the Textbox
  6. MyInProperty is set with 'X'
  7. MyOutProperty is set with 'The textbox below says: "X"'
  8. MyOutProperty's Set method calls RaisePropertyChanged passing in "MyOutProperty"
  9. The TextBlock gets updated as expected.

I suspect your issue isn't with your base class, it is either with the implementation of your child classes OR in your bindings.

To help debug your bindings, follow the information at this link to configure visual studio for verbose binding trace output (ends up in the Output window or Immediate window, if you've configured that).

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