与 x 引用的 XAML 绑定不起作用,但与代码的相同绑定有效 - 为什么?

问题描述 投票:0回答:1

我有一个 ContentView,它公开了一个布尔属性,您可以将其绑定到:

    public static readonly BindableProperty ShowCurrentIntervalInfoProperty = BindableProperty.Create(nameof(ShowCurrentIntervalInfo), typeof(bool), typeof(WorkoutTimerBottomView), defaultBindingMode: BindingMode.TwoWay);

    public bool ShowCurrentIntervalInfo
    {
        get => (bool)GetValue(ShowCurrentIntervalInfoProperty);
        set => SetValue(ShowCurrentIntervalInfoProperty, value);
    }

在此 ContentView 的 XAML 中,有一些控件的值绑定到此属性。现在,为了演示我的问题,请考虑以下两个标签和按钮:

    <Label x:Name="label1" Text="{Binding Source={x:Reference workoutTimerBottomView}, Path=ShowCurrentIntervalInfo}"/>
    <Label x:Name= "label2"/>
    <Button Clicked="Button_Clicked"/>

后面的代码:

    protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (propertyName == nameof(ShowCurrentIntervalInfo))
        {
            label2.Text = ShowCurrentIntervalInfo.ToString();
        }
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        ShowCurrentIntervalInfo = !ShowCurrentIntervalInfo;
    }

-> 现在,当我单击按钮时,label2 的文本确实从 True 切换为 False,这要归功于上面显示的 OnPropertyChanged 代码,但 label1 的文本仍然绑定为 False。

我不确定这是否是一个已知问题,或者我是否误解了有关绑定的某些内容?

(注意:ContentView实例的名称与x:Reference一致,这个在ContentView标签中)

x:Name="workoutTimerBottomView"
c# xaml binding maui
1个回答
0
投票

BindableProperty 可以检测属性更改。所以你可以在

BindableProperty.Create
方法中注册一个属性更改的回调方法。该方法将检测 ShowCurrentIntervalInfoProperty 的值变化。然后您可以在其中添加一些逻辑(例如设置 label2 的值)。请考虑下面我的代码,

public static readonly BindableProperty ShowCurrentIntervalInfoProperty = BindableProperty.Create(nameof(ShowCurrentIntervalInfo), typeof(bool), typeof(WorkoutTimerBottomView), defaultBindingMode: BindingMode.TwoWay,propertyChanged:OnInfoPropertyChanged);

private static void OnInfoPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
    var obj = bindable as WorkoutTimerBottomView;
    obj.label2.Text = newValue.ToString();
}

效果很好。

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.