我有一个简单的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而不是parent(Data)。
我正在使用最新的Xamarin.Forms 4.8.0,.NET Standard 2.0和Visual Studio 2019 16.7.4。
3条答案
按热度按时间z4iuyo4d1#
我测试了xaml代码,它仍然工作正常。检查gif:https://us.v-cdn.net/5019960/uploads/editor/pd/aa0fp5pwnvkl.gif
这里是相关代码,大家可以参考一下。
Page.xaml
字符串
Page.xaml.cs
型
Model类和ViewModel类
型
8qgya5xd2#
我试着运行你的代码,看到它没有什么问题,除了一些轻微的错别字在你的问题,我有它作为这个
字符串
,也许可以尝试清理/重建解决方案并再次运行?
x1c 0d1x的数据
7vux5j2d3#
要在此结束循环...正如@MilanM在10-17-20上评论的那样,他通过从xaml中删除这个来使它工作
字符串
我想其他人会说代码运行得很好,因为他们的xaml中从来没有这一行。@MilanM在他发表评论之前从未展示过。
我从我的xaml中删除了2行,然后一切正常。
型
注意:我在代码隐藏中使用以下内容设置了BindingContext:
型
高温高压