This project is read-only.

PropertyObserver : what am I doing wrong ?

Feb 15, 2010 at 5:57 PM
Edited Mar 2, 2010 at 8:20 AM

Hello, I can't get the PropertyObserver to work.

Window1.xaml :

<Window x:Class="TestPropertyObserver.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding TextValue}"></TextBox>
            <Button>Test</Button>
        </StackPanel>
    </Grid>
</Window>

Window1.xaml.cs :

public partial class Window1 : Window
    {
        public Window1()
        {
            this.InitializeComponent();

            ViewModel viewModel = new ViewModel();

            this.DataContext = viewModel;

            new PropertyObserver<ViewModel>(viewModel).RegisterHandler(x => x.TextValue,
                                                      model => Debug.WriteLine("In observer"));
        }
    }

ViewModel.cs :

public class ViewModel : ObservableObject
    {
        private string textValue;

        public string TextValue
        {
            get { return this.textValue; }
            set
            {
                this.textValue = value;
                this.RaisePropertyChanged("TextValue");
                Debug.WriteLine("In setter");
            }
        }
    }

The text "In setter" is displayed but not the text "In observer"

Any ideas why ? Thanks

Edit: I got it: seems like I have to keep the a reference to the PropertyObserver instance for it to work

Mar 9, 2010 at 8:03 PM

Hi,

Sorry the for the late reply, I've been very busy.  You nailed it with your EDIT on the original post.  Since PropertyObserver uses a weak event handler for the source object's PropertyChanged event, you must root the instance somewhere.  Otherwise the GC will collect the instance and your event handling method will never be invoked.

Thanks,

Josh