将多个按钮绑定到可观察集合中的各个项目

时间:2017-11-30 14:33:50

标签: c# wpf xaml data-binding

如果我的某个班级中有一个ObservableCollection。在我的视图后面的代码中,我有一个这个类的对象,并将其用作DataBinding

 this.DataContext = MyCustomClass;

在视图的xaml代码中我想将几个按钮绑定到Observable集合中的项目。像这样:

<Button x:Name="Bid_Price_10" Grid.Row="0" Content="{Binding myObservableCollection[0].Price, Mode=OneWay}" Grid.ColumnSpan="2" HorizontalAlignment="Stretch"  UseLayoutRounding="True" Padding="0"/>

 <Button x:Name="Bid_Price_11" Grid.Row="1" Content="{Binding myObservableCollection[1].Price, Mode=OneWay}" Grid.ColumnSpan="2" HorizontalAlignment="Stretch"  UseLayoutRounding="True" Padding="0"/>   

目前这不起作用,我错过了什么吗?

编辑:创建完整代码以演示我想要做的事情:

所以我有一个咖啡课:

class Coffee
{
    public int price { get; set; }
}

我有一个饮料类,里面有一份咖啡清单:

 class Drinks
{
    public List<Coffee> CoffeeList;

    public Drinks()
    {
        CoffeeList = new List<Coffee>();

        for (int i = 0; i < 10; i++)
        {
            Coffee c = new Coffee();
            c.price = i;
            CoffeeList.Add(c);
        }

        this.startCoffeePriceUpdateThread();
    }

    private void UpdateCofffeePrice()
    {

        while (true)
        {
            Thread.Sleep(1000);
            foreach (var c in CoffeeList)
            {
                c.price++;
            }
        } 
    }

    public void startCoffeePriceUpdateThread()
    {

            Thread coffeeThread = new Thread(new ThreadStart(UpdateCofffeePrice));
            coffeeThread.Start();       
    }
}

我的主窗口代码背后:

  public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Drinks ourDrinks = new Drinks();
        this.DataContext = ourDrinks;
    }
}

和我的xaml代码:

<Grid x:Name="Grid" HorizontalAlignment="Left" Height="193" Margin="77,31,0,0" VerticalAlignment="Top" Width="315">
  <Button x:Name="Button" Content="{Binding CoffeeList[0].Price}" HorizontalAlignment="Left" Margin="49,25,0,0" VerticalAlignment="Top" Width="75" Height="28"/>
</Grid>

所以问题是我没有看到按钮中的任何内容。目前我没有使用INotifyPropertyChange,因为我被告知不需要它。

1 个答案:

答案 0 :(得分:0)

正如Clemens建议的那样:如果一切都已修复,那么您将不再需要ObservableCollectionPropertyChanged通知。以下代码应该足够了:

public class Stuff
{
    public string Price { get; set; }
}

public class myCustomClass
{
    public List<Stuff> myCollection { get; set; }
}

public partial class MainWindow : Window
{

    public myCustomClass myCustomInstance = new myCustomClass();

    public MainWindow()
    {
        InitializeComponent();
        myCustomInstance.myCollection = new List<Stuff>();
        myCustomInstance.myCollection.Add(new Stuff() { Price = "1200$" });
        myCustomInstance.myCollection.Add(new Stuff() { Price = "5.5$" });
        this.DataContext = myCustomInstance;
    }
}

简化的XAML

    <Button Content="{Binding myCollection[0].Price, Mode=OneWay}"/>
    <Button Content="{Binding myCollection[1].Price, Mode=OneWay}" />

注意:我将myCustomClass的实例指定为DataContext。如果你真的需要将它绑定到类,请告诉我,我将更新代码。