0

こんにちは、ItemsSource を ObservableCollection にバインドしようとしています。ObservableCollection が公開されている場合、ObservableCollection は IntelliSense イベントによって認識されないようです。

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 プロパティ (MainWindow) にバインドする必要があります。

ポインタをありがとう。

編集:

これは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>
4

1 に答える 1

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;
}
于 2012-04-13T18:42:14.497 に答える