MVVM - RaisePropertyChanged turning code into a mess

前端 未结 5 2016
萌比男神i
萌比男神i 2021-01-12 00:08

New to MVVM so please excuse my ignorance.

I THINK i\'m using it right but I find my ViewModel has too many of these:

RaisePropertyChanged(\"SomeProp         


        
5条回答
  •  不要未来只要你来
    2021-01-12 00:24

    It does not get you back to the clean code, but I use a simple extension method to get the property name to avoid problems with magic strings. It also maintains the readability of the code, i.e. it is explicit what is happening.

    The extension method is simply as follows:

    public static string GetPropertyName(this MethodBase methodBase)
    {
        return methodBase.Name.Substring(4);
    }
    

    With this it means that you property sets are resilient against name changes and look like the following:

    private string _name;
    public string Name
    {
        get { return _name; }
        set 
        {
                name = value;
                RaisePropertyChanged(MethodBase.GetCurrentMethod().GetPropertyName()); 
        }
    }
    

    I've written more about this extension method here and I've published a matching code snippet here.

提交回复
热议问题