我的绑定:
<local:MyContentView BindingContext="{Binding Source={x:Reference Root}, Path=BindingContext.Entity.Recipe, Mode=OneWay}"/>
更改配方时,将更新ContentView上的BindingContext,但是MyContentView内的控件未填充数据。如果Recipe是有效值,则最初将用数据填充MyContentView内的控件,但是如果Recipe以null开头并更改为有效目标,则即使BindingContext更改,控件也不会更新。
答案 0 :(得分:0)
根据您的描述,您希望将contentview绑定到内容页面中,当数据源发生更改时数据不会更新,我想您可能没有为食谱实现 INotifypropertychanged ,您可以按照然后下一篇文章实现INotifyPropertyChanged。
https://xamarinhelp.com/xamarin-forms-binding/
使用 Bindableproperty 的另一种方法,我为您制作了一个示例,您可以看一下:
Contentview:
<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!";
}
}