2012-04-13 4 views
0

Здравствуйте, я пытаюсь связать ItemSource с 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"); 
     } 
    } 
} 

Насколько мне известно, что связывание должно связываться с имуществом StringList текущего DataContext, который MainWindow.

Спасибо за любой указатель.

Edit:

Это работает для меня в 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

У меня возникли проблемы с расшифровкой вашей проблемы? Не компилируется ли этот код? Не удается ли обновить список при запуске? –

ответ

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; 
} 
Смежные вопросы