为什么我的组合框绑定不起作用

时间:2015-09-19 17:26:38

标签: c# wpf

我试图将我的组合与列表绑定,但我什么都没得到

    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();

        List<item> list = new List<item>();
        list.Add(new item() {id = 1,name = "stack"});
        list.Add(new item() { id = 2, name = "overflow" });
        comboBox.DataContext = list;
        comboBox.SelectedIndex = 0;
    }

     <ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="22,14,0,0" VerticalAlignment="Top" Width="147" 

                ItemsSource="{Binding Path=list}" >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Label Content="{Binding Path=id}" />
                    <Label Content=":" />
                    <Label Content="{Binding Path=name}" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

1 个答案:

答案 0 :(得分:0)

您正在设置comboBox.DataContext = list;DataContext=this这不是MVVM的工作方式。此外,您永远不应该访问此背后的代码中的元素,这完全违反了MVVM原则。

相反,你应该做

   public List<Item> List { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        List = new List<Item>();
        List.Add(new Item() { id = 1, name = "stack" });
        List.Add(new Item() { id = 2, name = "overflow" });

        DataContext = this; //This is the only place where you should set datacontext
    }


   <ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="22,14,0,0" 
    VerticalAlignment="Top" Width="147" ItemsSource="{Binding List}" SelectedIndex=0 >