代码改变世界

WPF 绑定四(层级绑定)

2013-09-14 12:32  哒不溜  阅读(810)  评论(0编辑  收藏  举报

xaml:

<Window x:Class="WpfApplication1.Window4"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window4" Height="371" Width="507">
    <Grid>
        <StackPanel Margin="10,10,12,12" Name="stackPanel1">
            <TextBox Height="23" Margin="10" Name="textBox1" Width="120" />
            <TextBox Height="23" Margin="10" Name="textBox2" Width="120" />
            <TextBox Height="23" Margin="10" Name="textBox3" Width="120" />
        </StackPanel>
    </Grid>
</Window>

cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Window4.xaml 的交互逻辑
    /// </summary>
    public partial class Window4 : Window
    {
        public Window4()
        {
            InitializeComponent();
            List<Contry> infos = new List<Contry>() 
            { 
                new Contry() { 
                Name = "中国", 
                Provinces= new List<Province>(){
                    
                    new Province(){ 
                        Name="四川",
                        Citys=new List<City>(){
                            new  City(){
                                Name="绵阳市"
            }}}}}};
            this.textBox1.SetBinding(TextBox.TextProperty, new Binding("/Name") { Source=infos});
            this.textBox2.SetBinding(TextBox.TextProperty, new Binding("/Provinces/Name") { Source = infos });
            this.textBox3.SetBinding(TextBox.TextProperty, new Binding("/Provinces/Citys/Name") { Source = infos });
        }
    }

     class City
    {
        public string Name { set; get; }
    }

    class Province
    {
        public string Name { set; get; }
        public List<City> Citys { set; get; }
    }

    class Contry
    {
        public string Name { set; get; }
        public List<Province> Provinces { get; set; }
    }
}