Question

If a class property is Two-way bound to the text property of a textbox, when I change the text in the text box, is the "PropertyChanged" event of the class supposed to fire? It doesn't in my case - the message box never pops up when I change the text box content. The binding works though, if the properties change the textbox changes, and vice versa.

Edit: Now I realize it fires, but only when the textbox loses focus. I guess there must be a reason behind this behavior.

Code:

    public class BaselineAreas : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private double _Impervious = 0;
        public double Impervious
        {
            get { return _Impervious; }
            set
            {
                if (value != this._Impervious)
                {
                    _Impervious = value;
                    NotifyPropertyChanged("Impervious");
                }
            }
        }
        private double _Pervious = 0;
        public double Pervious
        {
            get { return _Pervious; }
            set
            {
                if (value != this._Pervious)
                {
                    _Pervious = value;
                    NotifyPropertyChanged("Pervious");
                }
            }
        }
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

    private BaselineAreas baselineAreas = new BaselineAreas();

    public MainPage()
    {
        InitializeComponent();

        baselineAreas.Impervious = 100;
        baselineAreas.Pervious = 500;
        textBoxTotalImperviousArea.DataContext = baselineAreas;
        textBoxTotalPerviousArea.DataContext = baselineAreas;
        baselineAreas.PropertyChanged += new PropertyChangedEventHandler(baselineAreas_PropertyChanged);
    }

    void baselineAreas_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        MessageBox.Show(baselineAreas.Impervious.ToString());
    }

Xaml:

                <TextBox Height="23" HorizontalAlignment="Left" Margin="138,16,0,0" Name="textBoxTotalImperviousArea" VerticalAlignment="Top" Width="62" 
                         Text="{Binding Impervious, Mode=TwoWay}"/>
                <TextBox Height="23" HorizontalAlignment="Right" Margin="0,45,226,0" Name="textBoxTotalPerviousArea" VerticalAlignment="Top" Width="62" 
                         Text="{Binding Pervious, Mode=TwoWay}"/> 
Was it helpful?

Solution

It's possible to give the textbox a behavior in your XAML to make it update on every character change:

http://dotneteers.net/blogs/vbandi/archive/2009/12/24/make-a-silverlight-textbox-update-its-binding-on-every-character.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top