2012年12月20日木曜日

Binding data to ListBox in WPF

It is simple to bind data to listbox in windows form.
Just drag a listbox control to the form and name it "listBox1".
Then assign data to the datasource ( here, I read an array of string from the file).

namespace DatatBindingDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.listBox1.DataSource = File.ReadAllText(@"C:\Users\Z\Desktop\DatatBindingDemo\Days.txt").Split();
        }
    }
}
In WPF, you have to do it in another way.
There is no datasource in listbox.
First, in MainWindow.xaml.cs

using System.IO;
using System.Windows;

namespace WpfDataBindingDemo
{
    public class MyData
    {
        public static string[] Days
        { get
            {
                return File.ReadAllText(@"C:\Users\Z\Desktop\WpfDataBindingDemo\Days.txt").Split();
            }
        }
    }

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

And in MainWindow.xaml

<Window x:Class="WpfDataBindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfDataBindingDemo"
        Title="MainWindow"
        Width="525"
        Height="350">
    <Grid>
        <ListBox ItemsSource="{Binding DataContext.Days, RelativeSource={RelativeSource Self}}">
            <ListBox.DataContext>
                <local:MyData />
            </ListBox.DataContext>
        </ListBox>
    </Grid>
</Window>

Notice that first you have to add reference to CLR by xmlns:local
then attach MyData to listbox datacontext. (obtained from local)
finally bind the itemsource to the datacontext by using {Binding...}

p.s. It is not necessary to use the word local. You can use any word you like in xmlns:local.

0 件のコメント:

コメントを投稿