【问题标题】:How to refresh binding data in silverlight mvvm using NotificationObject如何使用 NotificationObject 在 silverlight mvvm 中刷新绑定数据
【发布时间】:2012-10-22 16:21:53
【问题描述】:

我正在处理文本框所需的 TimeSpan 值。输入内容需要经过验证,并且可能采用多种不同的格式(例如 1300 表示 13:00)。我做了一些工作来检查并在视图模型中转换它。但在那之后如何刷新文本框中的文本?

<TextBox Text="{Binding Path= OpenHourFromText, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" ></TextBox>

OpenHourFromValue 是我用于验证和数据绑定的字符串属性

    public class MainPageViewModel : NotificationObject{
        public string OpenHourFromText
                {
                    get
                    {
    //OpenHourFrom is a TimeSpan property that contain the value
                        if (OpenHourFrom != null)
                        {
                            return GetOpeningHourText(OpenHourFrom); //fomat the time
                        }
                        else
                        {
                            return "";
                        }
                    }
                    set
                    {
//do validation and convert here. 1300 will be changed to 13:00 TimeSpan type
                        OpenHourFrom = ConvertToTimeSpan(value);  
                        RaisePropertyChanged("OpenHourFromText");
                    }
                }

        public TimeSpan OpenHourFrom { get; set; }

}

视图模型继承自 Microsoft.Practices.Prism.ViewModel.NotificationObject

在文本框中输入 1300 后,OpenHourFrom 会更新。但是文本框的文本没有更改为 13:00。为什么?请帮忙,谢谢。

【问题讨论】:

    标签: silverlight mvvm binding


    【解决方案1】:

    当TextBox设置一些值时它不会调用get。解决这个问题可以像用Dispatcher替换RaisePropertyChanged("OpenHourFromText")。BeginInvoke(() => RaisePropertyChanged("OpenHourFromText"));它会延迟触发该事件。

    set 
       { 
        //do validation and convert here. 1300 will be changed to 13:00 TimeSpan type 
         OpenHourFrom = ConvertToTimeSpan(value);                                            
         Dispatcher.BeginInvoke(() => RaisePropertyChanged("OpenHourFromText"));
       }
    

    【讨论】:

      【解决方案2】:

      您正在为属性 UpdateTimeText 发出 PropertyChange 通知,而您的实际属性名称是 OpenHourFromText

      更改您的 PropertyChange 通知以引发正确属性的通知,它应该会为您更新。

      【讨论】:

      • 对不起,我错误地粘贴了代码,在我的源代码中是 OpenHourFromText。但这对我不起作用。
      • @aiyagaze 如果在绑定中设置UpdateSourceTrigger=PropertyChanged 是否有效?默认为LostFocus,表示只有在失去焦点时才会更新源
      猜你喜欢
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 2019-07-13
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多