将 ObservableCollection 绑定到 WPF ListBox [英] Binding ObservableCollection to WPF ListBox

查看:30
本文介绍了将 ObservableCollection 绑定到 WPF ListBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码隐藏:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        ObservableCollection<int> sampleData = new ObservableCollection<int>();
        public ObservableCollection<int> SampleData
        {
            get
            {
                if (sampleData.Count <= 0)
                {
                    sampleData.Add(1);
                    sampleData.Add(2);
                    sampleData.Add(3);
                    sampleData.Add(4);
                }
                return sampleData;
            }
        }
    }

我的 xaml 是:

<Window x:Class="Sandbox.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">
    <Grid>
        <ListBox ItemsSource="{Binding Path=SampleData}"/>
    </Grid>
</Window>

该列表不显示集合中的值(或根本不显示任何值).有人能指出我的错误是什么吗?

The list doesn't display the values in the collection (or anything at all). Can someone point out what my mistake is?

我需要明确设置 DataContext 吗?我想如果没有设置控件将只使用自己作为 DataContext.

Do I need to set the DataContext explicitly? I thought if none is set the control will just use itself as the DataContext.

推荐答案

是的,您需要以某种方式设置 DataContext.它没有 DataContext,因为除非设置,否则 Window 没有 DataContext.如果您在构造函数中执行此操作,ListBox 将获得 DataContext.

Yes, you'll need to set the DataContext somehow. It doesn't have a DataContext, because the Window doesn't have a DataContext unless it is set. The ListBox will get the DataContext if you do this in the constructor.

public MainWindow() 
{ 
    InitializeComponent(); 
    this.DataContext = this;
} 

否则你可以在绑定中使用RelativeSource、ElementName等,但我猜你知道=)

Otherwise you can use RelativeSource, ElementName etc. in the Binding but I guess you knew that =)

这篇关于将 ObservableCollection 绑定到 WPF ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆