简体   繁体   中英

wpf binding listbox items to a static list

I really looked hard. There seems to be something I am missing. Using .net 4.5.

Here's my XAML:

<Window x:Class="a.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:a"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox x:Name="myListBox" HorizontalAlignment="Left" Height="201" Margin="144,33,0,0" VerticalAlignment="Top" Width="115" ItemsSource="{Binding (local:myClass.myStaticList)}"/>
        <Button Content="Button" HorizontalAlignment="Left" Height="48" Margin="282,247,0,0" VerticalAlignment="Top" Width="150" Click="Button_Click"/>

    </Grid>
</Window>

and here's the code behind:

using System.Collections.ObjectModel;
using System.Windows;

namespace a
{
    public class myClass
    {
        public static ObservableCollection<string> myStaticList { get; set; }
    }

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

            myListBox.Items.Add("aaa");
            myListBox.Items.Add("bbb");
            myListBox.Items.Add("ccc");
            myListBox.Items.Add("ddd");
            myListBox.Items.Add("eee");
            myListBox.Items.Add("rrr");

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            <--- Breakpoint here
        }
    }
}

Real simple. The button is used only to pause the running with a breakpoint and see whether the data was introduced from myListBox to myControl.myList .

It doesn't. myList remains null. What am I missing?

Help please! TIA

You have to create an instance and add data to your ObservableCollection , not to the ListBox that is binding to it.

MainWindow.cs :

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

        myClass.myStaticList = new ObservableCollection<string>();

        myClass.myStaticList.Add("aaa");
        myClass.myStaticList.Add("bbb");
        myClass.myStaticList.Add("ccc");
        myClass.myStaticList.Add("ddd");
        myClass.myStaticList.Add("eee");
        myClass.myStaticList.Add("fff");
    }
}

XAML :

<Grid>
    <ListBox x:Name="ListBox1" Margin="0" ItemsSource="{Binding myStaticList}">
        <ListBox.DataContext>
            <local:myClass/>
        </ListBox.DataContext>
    </ListBox>
</Grid>

Result:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM