C# 将按钮文本绑定到ObservableCollection
我正在尝试一些简单的事情,比如设置按钮的列表视图,并将这些按钮的文本绑定到列表中的元素 这是测试主页C# 将按钮文本绑定到ObservableCollection,c#,xamarin,binding,xamarin.forms,C#,Xamarin,Binding,Xamarin.forms,我正在尝试一些简单的事情,比如设置按钮的列表视图,并将这些按钮的文本绑定到列表中的元素 这是测试主页 public MainPage() { InitializeComponent(); ObservableCollection<Lot> lotList = new ObservableCollection<Lot>(); lotList.Add(new Lot(1)); lot
public MainPage()
{
InitializeComponent();
ObservableCollection<Lot> lotList = new ObservableCollection<Lot>();
lotList.Add(new Lot(1));
lotList.Add(new Lot(2));
lotList.Add(new Lot(3));
lotList.Add(new Lot(4));
lotList.Add(new Lot(5));
this.BindingContext = lotList;
}
您可以做的是将{Binding}更改为{Binding Name}
希望有帮助 你能和我们分享一下Lot模型吗?我刚做了,谢谢你的兴趣!谢谢,它起作用了。我会把这当作一个答案。你认为这种类型的绑定是最好的方式吗?如果没有更多的上下文,没有人能够回答一个最好的问题,但你所拥有的是一种完全正常的做事模式的一部分,这很好:这很好。您也可以使用{x:Bind},但对我来说,这看起来好多了。
<ListView x:Name="lotListView" HorizontalOptions="Center" ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Button Text="{Binding}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
public class Lot
{
private int id { get; set; }
public String Name { get; set; }
public Lot(int id)
{
this.id = id;
this.Name = "Lot n° " + id.ToString();
}
}
<ListView x:Name="lotListView" HorizontalOptions="Center" ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Button Text="{Binding Name}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>