【发布时间】:2021-01-13 06:26:15
【问题描述】:
我有一个简单的 XAML 页面,代码如下:
<StackLayout BindableLayout.ItemsSource="{Binding Data}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label BackgroundColor="{Binding Color}"
Text="{Binding Text}"
FontAttributes="Italic"
FontSize="20"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
HeightRequest="105"
Margin="25" />
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
在我后面的查看页面代码中:
public partial class DataView
{
public DataView()
{
InitializeComponent();
BindingContext = new ViewModel();
}
...
}
数据是:
public class ViewModel
{
public ViewModel()
{
Data = new ObservableCollection()<Model> {
new Model { Text = "Pink", Color = Color.DeepPink },
new Model { Text = "Crimson", Color = Color.Crimson },
new Model { Text = "Aqua", Color = Color.Aqua },
new Model { Text = "Blue", Color = Color.DeepSkyBlue },
new Model { Text = "BurlyWood", Color = Color.BurlyWood }, };
}
public ObservableCollection<Model> Data { get; set; }
}
public class Model
{
public Color Color { get; set; }
public string Text { get; set; }
}
但是,在编译时,我得到:
绑定:在“MyComp.ViewModel”上找不到属性“Color”。
似乎它在 ViewModel 中搜索 Color 而不是父级(数据)。
我正在使用最新的 Xamarin.Forms 4.8.0、.NET Standard 2.0 和 Visual Studio 2019 16.7.4。
【问题讨论】:
-
尝试使用 Color 以外的名称重命名您的属性
-
用 ColorTyp 试过了,还是一样。在编译时失败并出现此错误。
-
我创建了一个基本示例来测试您的代码,它工作正常。尝试清理项目的 obj 和 bin 文件夹,然后重新构建。 'ViewModel' 类的代码应如下所示,确保引用正确的包。
public class ViewModel { public ViewModel() { Data = new System.Collections.ObjectModel.ObservableCollection<Model>() {...}; } public ObservableCollection<Model> Data { get; set; } } -
根据描述无法重现问题,请贴出相关代码。如果您确认这是一个潜在问题,您可以在 github 上报告该问题。
-
我贴了相关代码,你可以参考一下。
标签: xamarin xamarin.forms binding