Change Background Color for WPF textbox in changed-state

前端 未结 6 1643
故里飘歌
故里飘歌 2020-12-15 01:19

I have a class EmployeeViewModel with 2 properties \"FirstName\" and \"LastName\". The class also has a dictionary with the changes of the properties. (The class implements

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 01:44

    A complete diferent way would be to not implement INotifyPropertyChanged and instead descend from DependencyObject or UIElement

    They implement the binding using DependencyProperty You may event use only one event handler and user e.Property to find the rigth textbox

    I'm pretty sure the e.NewValue != e.OldValue check is redundant as the binding should not have changed. I also beleive there may be a way to implement the binding so the dependecyObject is the textbox and not your object...

    Edit if you already inherit from any WPF class (like control or usercontrol) you are probably ok and you don't need to change to UIElement as most of WPF inherit from that class

    Then you can have:

    using System.Windows;
    namespace YourNameSpace
    {
    class PersonViewer:UIElement
    {
    
        //DependencyProperty FirstName
        public static readonly DependencyProperty FirstNameProperty =
            DependencyProperty.Register("FirstName", typeof (string), typeof (PersonViewer),
                                        new FrameworkPropertyMetadata("DefaultPersonName", FirstNameChangedCallback));
    
        public string FirstName {
            set { SetValue(FirstNameProperty, value); }
            get { return (string) GetValue(FirstNameProperty); }
        }
    
        private static void FirstNameChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) {
    
            PersonViewer owner = d as PersonViewer;
            if (owner != null) {
                if(e.NewValue != e.OldValue && e.NewValue != "DefaultPersonName" ) {
    
                    //Set Textbox to changed state here
    
                }
            }
    
        }
    
        public void AcceptPersonChanges() {
    
            //Set Textbox to not changed here
    
        }
    
     }
    }
    

提交回复
热议问题