Unable to bind to static property in parent viewmodel in xaml?

LeloLelo Member ✭✭✭
edited October 2018 in Xamarin.Forms

I need to set a commandparameter binding to a static property in the parent class of the viewmodel that is the binding context of the page. Do I have to set path and not just bind it to the property name like usual? CommandParameter="{Binding PropertyName}" // of static property in parent bindingcontext . If I have to set a path what would how would the CommandParameter setting look like?

Best Answer

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    Why do you want to bind to a static property? Since your binding context must be an instance of your class, we can just bind to a normal property. But we can use normal property to pass data to static property. Here is the code:

    public class MyModel : INotifyPropertyChanged
    {
        public static string MyStaticName { set; get; }
    
        public string MyName
        {
            set
            {
                MyStaticName = value;
                onPropertyChanged("MyName");
            }
            get
            {
                return MyStaticName;
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        void onPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    Just bind your control to this MyName, then when its value changed the static property will also change.

  • LeloLelo Member ✭✭✭

    I have some trouble with CommandParameter and evaluating my object. It does not appear to bind properly. The CanExecute method is not called when MyStaticName is changing. In my scenario MyStaticName is a model that contains the input of two properties - from another ViewModel than the ViewModel set as BindingContext - and one property from the BindingContext ViewModel. Calling (equivalent) OnPropertyChanged("MyName") from the setter of these two properties neither makes it work.

    The CommandParameter is binded to "MyName" property.

  • LandLuLandLu Member, Xamarin Team Xamurai
    edited October 2018

    @Lelo Please share your code(both xaml and your ViewModel). Then describe more clearly about what you want to achieve.

  • cbdcbd Member ✭✭

    You can't bind to a static property as it is not possible for the framework to raise OnPropertyChanged changed events nor attach handlers through Binding unless the property is associated with a specific class instance.

    A static property is not instantiated and as such has exactly the same value for all instances of the class to which it is a member.

Sign In or Register to comment.