xaml - 绑定 ContentView 的 BindingContext 不会更新里面的控件
问题描述
我的绑定:
<local:MyContentView BindingContext="{Binding Source={x:Reference Root}, Path=BindingContext.Entity.Recipe, Mode=OneWay}"/>
更改配方时,ContentView 上的 BindingContext 正在更新,但 MyContentView 中的控件未填充数据。如果 Recipe 最初是一个有效值,则 MyContentView 中的控件将填充数据,但如果 Recipe 以 null 开始并更改为有效目标,则尽管 BindingContext 更改,控件仍不会更新。
解决方案
根据您的描述,您想在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!";
}
}
推荐阅读
- jgit - 来自 git.pull().call() 的受影响文件列表
- udp - 如何使用 Gstreamer 命令行在数据包中发送一行
- python - 按值排序字典
- c# - 为什么我的跳跃动画在中间停止并返回空闲?
- angularjs - 将此多重条件转换为 ng 类条件
- kubernetes - 如何专门为 Pod 创建 PV
- java - 如何在多个服务器中处理相同的多个请求
- r - 我收到“错误!环形:无效的参数类型”
- angular - 如何使用自定义排序算法对 prime-ng 数据表的特定列进行排序
- java - CustomAuthenticationProcessingFilter 中的 HashMap