首页 > 解决方案 > 绑定 ContentView 的 BindingContext 不会更新里面的控件

问题描述

我的绑定:

<local:MyContentView BindingContext="{Binding Source={x:Reference Root}, Path=BindingContext.Entity.Recipe, Mode=OneWay}"/>

更改配方时,ContentView 上的 BindingContext 正在更新,但 MyContentView 中的控件未填充数据。如果 Recipe 最初是一个有效值,则 MyContentView 中的控件将填充数据,但如果 R​​ecipe 以 null 开始并更改为有效目标,则尽管 BindingContext 更改,控件仍不会更新。

标签: xamlxamarin.forms

解决方案


根据您的描述,您想在contentpage中绑定contentview,数据源更改时数据不更新,我猜您可能没有为Recipe实现INotifypropertychanged,您可以按照下面的文章来实现INotifyPropertyChanged。

https://xamarinhelp.com/xamarin-forms-binding/

使用Bindableproperty的另一种方式,我为你做了一个示例,你可以看看:

内容视图:

<ContentView.Content>
  <StackLayout>
        <Label x:Name="label1" Text="{Binding Text}" />

    </StackLayout>

public partial class mycontenview : ContentView
{


    public static BindableProperty TextProperty = BindableProperty.Create(
propertyName: "Text",
returnType: typeof(string),
declaringType: typeof(mycontenview),
defaultValue: string.Empty,
defaultBindingMode: BindingMode.OneWay,
propertyChanged: HandlePropertyChanged);


    public string Text
    {
        get
        {
            return (string)GetValue(TextProperty);
        }
        set
        {
            SetValue(TextProperty, value);
        }
    }
    private static void HandlePropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        mycontenview contentview = bindable as mycontenview;
        contentview.label1.Text = newValue.ToString();

    }


    public mycontenview()
    {
        InitializeComponent();

    }
}

主页:

<StackLayout>
    <Label Text="welcome to xamarin world!"/>
    <Button x:Name="btn1" Text="btn1" Clicked="btn1_Clicked"/>
    <local:mycontenview  Text="{Binding str}"/>
</StackLayout>

public partial class MainPage : ContentPage, INotifyPropertyChanged
{

    private string _str;
    public string str
    {
        get { return _str; }
        set
        {
            _str = value;
            OnPropertyChanged("str");
        }
    }
    public MainPage()
    {
        InitializeComponent();
        m = new model1() { str = "test 1", str1 = "test another 1" };
        str = "cherry";
        this.BindingContext = this;
    }
    public event PropertyChangedEventHandler PropertyChanged;



    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs((propertyName)));
    }



    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(storage, value))
        {
            return false;
        }
        storage = value;
        OnPropertyChanged(propertyName);



        return true;
    }



    private void btn1_Clicked(object sender, EventArgs e)
    {
        str = "this is test!";
    }
}

推荐阅读