2012-04-13 45 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; 
} 
相關問題