Change Background Color for WPF textbox in changed-state

前端 未结 6 1624
故里飘歌
故里飘歌 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:48

    If you're using the MVVM paradigm, you should consider the ViewModels as having the role of adapters between the Model and the View.

    It is not expected of the ViewModel to be completely agnostic of the existence of a UI in every way, but to be agnostic of any specific UI.

    So, the ViewModel can (and should) have the functionality of as many Converters as possible. The practical example here would be this:

    Would a UI require to know if a text is equal to a default string?

    If the answer is yes, it's sufficient reason to implement an IsDefaultString property on a ViewModel.

    public class TextViewModel : ViewModelBase
    {
        private string theText;
    
        public string TheText
        {
            get { return theText; }
            set
            {
                if (value != theText)
                {
                    theText = value;
                    OnPropertyChanged("TheText");
                    OnPropertyChanged("IsTextDefault");
                }
            }
        }
    
        public bool IsTextDefault
        {
            get
            {
                return GetIsTextDefault(theText);
            }
        }
    
        private bool GetIsTextDefault(string text)
        {
            //implement here
        }
    }
    

    Then bind the TextBox like this:

    
        
            
        
    
    

    This propagates text back to the ViewModel upon TextBox losing focus, which causes a recalculation of the IsTextDefault. If you need to do this a lot of times or for many properties, you could even cook up some base class like DefaultManagerViewModel.

提交回复
热议问题