2015-09-19 25 views
0

我想我的组合绑定列表,但我什么也没有为什么我的组合框绑定不工作

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> 
+2

不要插入链接到外部网站。在这里发布代码的相关部分。 – Steve

+0

其带我有时小时,以适应我的代码到stackoverflow要求 – user4515101

回答

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 > 
+0

它不能正常工作 – user4515101

+0

你确定..因为它适用于我的机器..你可以发布你的代码 – Rohit

+0

https://dotnetfiddle.net/qzOs3I – user4515101

1

你有局部变量作为您的项目源。它必须是一个财产。

更改此:

public MainWindow() 
{ 
    .... 
    List<item> list = new List<item>(); 
    ... 
} 

要这样:

List<item> list { get; set; } 

public MainWindow() 
{ 
    .... 
    this.list = new List<item>(); 
    ... 
} 

而且,你不需要手动设置的datacontext组合框的构造函数(删除此行) :comboBox.DataContext = list;您正在将Xaml中的datacontext设置为:ItemsSource="{Binding Path=list}"

您的代码还存在其他问题。您没有更改INotifyProperty,因此,数据只会在intstatiation时加载一次。此外,您不应该将自己的数据上下文绑定到UI组件本身。正确的做法是使用ViewModel类。