首页 文章

在TwoWay绑定中通知目标更改的来源

提问于
浏览
1

我正在构建一个Windows应用商店应用程序,我有一个TextBox绑定(双向模式)到我的TaskItem对象的字符串“title”属性 .

在对此TextBox进行UI更改并将其传播回源之后,我需要进行一些处理 .

我'd like to know if there'是一种检测目标的方法(TextBox 's Text property) has changed. I know I can catch this event by handling the TextBox' s LostFocus事件,但是在更新源之前触发了此事件 .

Update:

捆绑:

<ScrollViewer
            x:Name="itemDetail"
            DataContext="{Binding SelectedItem, ElementName=itemListView}">
    <TextBox x:Name="itemTitle" Text="{Binding Title, Mode=TwoWay}"/>
</ScrollViewer>

类和 property :

class TaskItem
{
    public string Title { get; set; }
}

我没有实现INotifyPropertyChanged,因为我实际上不需要将更改从源传播到目标 .

我可以想到两个解决方案:

  • 有没有办法在属性的setter上使用[CallerMemberName]?如果有,我可能能够确定"title"是由我自己的代码更改还是由于绑定 .

  • 抛弃双向绑定并在LostFocus事件期间手动更新源 .

1 回答

  • 1
    class TaskItem, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        internal void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    
        private string title;
        public string Title 
        { 
           get { return title; } 
           set 
           { 
               if (title == value) return;
               title = value;
               NotifyPropertyChanged("Title");
           }
        }
        public TaskItem (string -title) 
        { title = _title; }  
        // does not fire setter title lower case 
        // but the UI will have this value as ctor fires before render 
        // so get will reference the assigned value of title 
    }
    

    Constructor Design

相关问题