【发布时间】:2021-04-20 19:26:58
【问题描述】:
我在使用 Binding 在 Listview 中使用自定义控件时遇到问题。 我给你我的代码,让它更具体。
我的自定义控件(FridgeControl)
Xaml:
<ContentView.Content>
<StackLayout>
<Label x:Name="LabelName" Text="{Binding Source={x:Reference FridgeView}, Path=NameFridge }" />
</StackLayout>
</ContentView.Content>
Cs:
public partial class FridgeControl : ContentView
{
public string NameFridge { get; set; }
public static readonly BindableProperty NameFridgeProperty = BindableProperty.Create(
propertyName: "NameFridge",
returnType: typeof(string),
declaringType: typeof(FridgeControl),
defaultValue: "");
public FridgeControl ()
{
InitializeComponent ();
}
}
我的页面(FridgePage)
Xaml:
<ContentPage.Content>
<StackLayout>
<ListView x:Name="ListFridges"
ItemsSource="{Binding Fridges}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<c:FridgeControl NameFridge="{Binding Name}"></c:FridgeControl>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
Cs:
public partial class FridgesPages : ContentPage
{
public ObservableCollection<Fridge> Fridges { get; private set; }
public FridgesPages()
{
InitializeComponent();
this.Fridges = new ObservableCollection<Fridge>()
{
new Fridge
{
Id = 1,
Name = "Garage",
Foods = new List<Food>()
{
new Food
{
Id = 14,
Name = "Tomatoes",
Type = Models.Enum.TypeFoodEnum.Vegetal,
MaxDate = new DateTime(2021, 01, 20)
},
new Food
{
Id = 6,
Name = "Chicken",
Type = Models.Enum.TypeFoodEnum.Meat,
MaxDate = new DateTime(2021, 01, 15)
},
new Food
{
Id = 44,
Name = "Water",
Type = Models.Enum.TypeFoodEnum.Drink,
},
}
},
new Fridge
{
Id = 1,
Name = "Kitchen",
Foods = new List<Food>()
{
new Food
{
Id = 14,
Name = "Salad",
Type = Models.Enum.TypeFoodEnum.Vegetal,
MaxDate = new DateTime(2021, 01, 20)
},
new Food
{
Id = 6,
Name = "Meat",
Type = Models.Enum.TypeFoodEnum.Meat,
MaxDate = new DateTime(2021, 01, 15)
},
new Food
{
Id = 44,
Name = "Juice",
Type = Models.Enum.TypeFoodEnum.Drink,
},
}
}
};
BindingContext = this;
}
}
对象冰箱:
public class Fridge
{
public int Id { get; set; }
public string Name { get; set; }
public List<Food> Foods { get; set; }
public Fridge() { }
}
当我进入 FridgePAge 页面时,我遇到了 Cast Exception。 我应该怎么做才能在 ListView 中使用我的自定义控件?
你能帮我找出我做错了什么吗?
谢谢。
【问题讨论】:
-
你的 Fridge 类是什么样子的——它有一个属性 Name 被定义为一个字符串吗?
-
如果数据寺庙部分可以有自己的模板,为什么还要在数据模板中使用自定义控件
-
感谢您的回答。 @Russ:我添加了冰箱对象。它确实有一个名为 Name 的属性
-
@Hammad Shabbir 我不明白你的回答。请问我应该如何正确地做呢? ListView 不直接接受孩子。
标签: c# xamarin.forms