2012-04-13 71 views
0

你好我正在尝试将一个ItemsSource绑定到一个ObservableCollection。如果ObservableCollection是公共的,看起来IntelliSense事件看不到ObservableCollection。为什么我的绑定不能在ObservableCollection上工作

我在XAML中声明了什么使它可见吗?像在Window.Ressources

我的XAML代码

<Window x:Class="ItemsContainer.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 

    <StackPanel Orientation="Horizontal"> 
     <ListBox ItemsSource="{Binding StringList}" /> 
    </StackPanel> </Window> 

我的C#代码

using System.Collections.ObjectModel; 
using System.Windows; 

namespace ItemsContainer 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 

     private ObservableCollection<string> stringList = new ObservableCollection<string>(); 

     public ObservableCollection<string> StringList 
     { 
      get 
      { 
       return this.stringList; 
      } 
      set 
      { 
       this.stringList = value; 
      } 
     } 

     public MainWindow() 
     { 
      InitializeComponent(); 
      this.stringList.Add("One"); 
      this.stringList.Add("Two"); 
      this.stringList.Add("Three"); 
      this.stringList.Add("Four"); 
      this.stringList.Add("Five"); 
      this.stringList.Add("Six"); 
     } 
    } 
} 

据我所知这应该结合绑定到当前 的DataContext的财产的StringList,这是主窗口。

感谢任何指针。

编辑:

这在XAML

<Window x:Class="ItemsContainer.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 

    <StackPanel Orientation="Horizontal"> 
     <ListBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=StringList}" /> 
    </StackPanel> 
</Window> 
+0

我无法破译你的问题?这段代码是不是编译?运行时列表是否无法更新? – 2012-04-13 18:39:23

回答

3

DataContext不默认为MainWindow工作对我来说,你必须明确地设定。像这样:

public MainWindow() { 
    InitializeComponent(); 
    this.stringList.Add("One"); 
    this.stringList.Add("Two"); 
    this.stringList.Add("Three"); 
    this.stringList.Add("Four"); 
    this.stringList.Add("Five"); 
    this.stringList.Add("Six"); 
    this.DataContext = this; 
} 
相关问题