Home > Back-end >  Binding does not work for Platform dependent Behaviors
Binding does not work for Platform dependent Behaviors

Time:11-29

Binding to observable property does not work when I try to create my own custom behavior. Neither it does in any of community mvvm toolkit platform behaviors:

https://github.com/CommunityToolkit/Maui/tree/main/src/CommunityToolkit.Maui/Behaviors/PlatformBehaviors

Take for example StatusBarBehavior, write something like

    <ContentPage.Behaviors>
        <toolkit:StatusBarBehavior StatusBarColor="{Binding StatusBarColorProp}" StatusBarStyle="LightContent" />
    </ContentPage.Behaviors>

create the property in your view model

    [ObservableProperty]
    private Color _statusBarColorProp;

you'll see status bar color does not change with StatusBarBehavior property change in runtime. Same for all the rest behaviors. It works fine for non-bindings setters like StatusBarColor="Red".

I wonder if it's a feature or a bug, or I'm missing something.

CodePudding user response:

I can replicate your issue. And it turns out that we can only change the color of the StatusBarColor either in code behind like below or non-bindings setters like StatusBarColor="Red" as you mentioned.

 <ContentPage.Behaviors> 
        <toolkit:StatusBarBehavior x:Name="statusBar" ></toolkit:StatusBarBehavior>
 </ContentPage.Behaviors>

private void OnCounterClicked(object sender, EventArgs e) 
{
   statusBar.StatusBarColor = Colors.Red;
}

It fails to change the color of StatusBarColor when binding to an observable property. This could be a potential issue and I would suggest that you can raise a Bug Report in Github.

CodePudding user response:

Please file a bug issue at github maui issues.

In the meantime, try this gross hack in one of your properties:

static public BindableProperty MyValueProperty = BindableProperty.Create(...,
  propertyChanged: (bindable, oldValue, newValue) =>
  {
    var it = (MyClass)bindable;
    // If it is changing, force explicit OnPropertyChanged. This is usually redundant,
    // but might help a binding "cascade" to dependencies.
    if (!(MyType)newValue.Equals((MyType)oldvalue))
      it.OnPropertyChanged(nameof(MyValue));
  });
public MyType MyValue
{
  get => (MyType)GetValue(MyValueProperty);
  set => SetValue(MyValueProperty, value);
}
  • Related