绑定不能用于依赖平台的行为



当我尝试创建自己的自定义行为时,绑定到可观察属性不起作用。在任何社区mvvm工具包平台行为中也不这样做:

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

StatusBarBehavior为例,写如下

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

在视图模型中创建属性

[ObservableProperty]
private Color _statusBarColorProp;

你会看到状态栏的颜色不会随着StatusBarBehavior属性在运行时的改变而改变。其他的行为也是一样。对于像StatusBarColor="Red"这样的非绑定设置器,它工作得很好。

我想知道这是一个功能还是一个bug,或者我遗漏了什么。

问题报告https://github.com/dotnet/maui/issues/11729

我可以复制你的问题。事实证明,我们只能改变StatusBarColor的颜色,或者像下面这样的代码后面,或者像你提到的StatusBarColor="Red"这样的非绑定设置。

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

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

当它绑定到一个可观察属性时,不能改变StatusBarColor的颜色。这可能是一个潜在的问题,我建议你可以在Github上提出一个Bug报告。

请在github maui issues上提交错误问题。

与此同时,在你的一个属性中尝试这个粗糙的hack:

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);
}

最新更新