Silverlight PropertyChanged事件未在双向文本框绑定中触发

时间:2013-04-05 20:00:29

标签: silverlight events binding propertychanged

如果类属性是双向绑定到文本框的text属性,当我更改文本框中的文本时,该类的“PropertyChanged”事件是否应该触发?它不是我的情况 - 当我更改文本框内容时,消息框永远不会弹出。但是,如果属性更改了文本框更改,则绑定有效,反之亦然。

编辑:现在我意识到它会触发,但只有当文本框失去焦点时才会触发。我想这种行为背后肯定有一个原因。

代码:

    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}"/> 

1 个答案:

答案 0 :(得分:0)

可以在XAML中为文本框提供一个行为,使其在每次更改字符时都会更新:

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