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

查看:303
本文介绍了将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;
} 

否则,您可以在Binding中使用RelativeSource,ElementName等,但是我想您知道=)

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

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

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