【问题标题】:Why my binding don't work on a ObservableCollection为什么我的绑定在 ObservableCollection 上不起作用
【发布时间】:2012-04-13 18:35:52
【问题描述】:

您好,我正在尝试将 ItemsSource 绑定到 ObservableCollection。如果 ObservableCollection 是公开的,那么 IntelliSense 事件似乎看不到 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。

感谢您的指点。

编辑:

这在 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>

【问题讨论】:

  • 我无法解读您的问题?这段代码不能编译吗?运行时列表是否更新失败?

标签: wpf binding observablecollection


【解决方案1】:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2011-01-16
    • 2012-08-26
    • 2012-01-17
    • 2011-09-29
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多