0

如果类属性双向绑定到文本框的文本属性,当我更改文本框中的文本时,是否应该触发该类的“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());
    }

xml:

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

1 回答 1

0

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

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

于 2013-04-06T09:30:59.853 回答