有一个绑定到字符串 ObservableCollection 的 ListView。 Listview 有一个标签和一个 ContentView(只包含一个标签)。 两者都绑定到同一个集合。
此外,还有一个按钮可以为集合生成一些随机数据。
问题是当我运行应用程序并单击“生成数据”按钮时,标签会更新,但不会更新 ContentView。
内容视图内的标签也应该改变。
内容视图内的标签保持不变
Nuget 包:
Xamarin.Forms
NET标准库
受影响的设备:
一周前在 stackoverflow 上询问 - https://stackoverflow.com/questions/50211197/xamarin-forms-user-control-binding-inside-listview
正在做
this.BindingContext = this;
在 MagicBox.xaml.cs 中强制 BindingContext 到当前对象。 这也意味着不再继承父级的 BindingContext。
为了使其工作,将您的代码更改为
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MagicBox : ContentView
{
public static readonly BindableProperty TextProperty =
BindableProperty.Create("Text", typeof(string), typeof(MagicBox), default(string));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public MagicBox ()
{
InitializeComponent ();
}
}
和你的 xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestSample.Controls.MagicBox"
x:Name="box">
<ContentView.Content>
<Grid>
<Label Text="{Binding Text, Source={x:Reference box}}" />
</Grid>
</ContentView.Content>
</ContentView>
谢谢@StephaneDelcroix ,它奏效了:)
最有用的评论
正在做
在 MagicBox.xaml.cs 中强制 BindingContext 到当前对象。 这也意味着不再继承父级的 BindingContext。
为了使其工作,将您的代码更改为
和你的 xaml