2017-03-09 60 views
0

我在尝试简单的事情,例如设置按钮的列表视图并将这些按钮的文本绑定到列表中的元素。绑定按钮文本到ObservableCollection

这里是测试MainPage。

 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; 
    } 

这是相当直接的,创建项目列表并添加项目到它。

的XAML看起来是这样的:

  <ListView x:Name="lotListView" HorizontalOptions="Center" ItemsSource="{Binding}"> 
      <ListView.ItemTemplate> 
       <DataTemplate> 
        <ViewCell> 
         <Button Text="{Binding}"/> 
        </ViewCell> 
       </DataTemplate> 
      </ListView.ItemTemplate> 
     </ListView> 

这是做我猜常见的事?

我确实显示了正确数量的按钮,但没有写入它们。 我的问题是:我如何使按钮的Text属性从列表中的项目获取名称? 我以为ToString方法会被调用,但看起来并不如此。

的很多课,根据要求:

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(); 
    } 
} 
+0

你能分享我们的地段模式吗? – mindOfAi

+0

我刚刚做了,感谢您的关注! –

回答

1

你可以做的是改变{Binding}{Binding Name}

<ListView x:Name="lotListView" HorizontalOptions="Center" ItemsSource="{Binding}"> 
      <ListView.ItemTemplate> 
       <DataTemplate> 
        <ViewCell> 
         <Button Text="{Binding Name}"/> 
        </ViewCell> 
       </DataTemplate> 
      </ListView.ItemTemplate> 
     </ListView> 

希望它能帮助!

+0

谢谢,它的工作原理。我会把它作为答案。 您认为这种绑定方式是“最好”的方式吗? –

+0

如果没有更多的上下文,没有人能够回答“最佳”问题,但是你拥有的是完美正常的处事模式的一部分,并且很好:) – Jason

+0

好的,谢谢你的输入! –

相关问题