发新话题
打印

WPF中treeview的数据绑定

WPF中treeview的数据绑定

不能像以前递归添加node,好像得用数据模板,我上网找了好久都没有这方面的例子,哪为研究过给个例子。


安装Windows SDK。里面Program Files\Microsoft SDKs\Windows\v6.0\Samples\WPFSamples有你想要的各种smaple

Give u simple sample


C# code
public class People
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class PeopleList : List<eople>
    {
        public PeopleList()
        {
            Add(new People() { Name = "Yohan", Age=26 });
            Add(new People() { Name = "Tom", Age = 27 });
            Add(new People() { Name = "Jerry", Age = 28 });
            Add(new People() { Name = "Monica", Age = 29 });
        }
    }





XAML code
<Window x:Class="WpfApplication3.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication3"
    Title="Window1" Height="300" Width="300" >
    <Window.Resources>
        <localeopleList x:Key="peopleList"/>
        <DataTemplate x:Key="treeviewItemStyle" DataType="{x:Type localeople}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text=" Name: "/>
                <TextBlock Background="Azure" Text="{Binding Path=Name}"/>
                <TextBlock Text=" | Age: "/>
                <TextBlock Background="Yellow" Text="{Binding Path=Age}"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <TreeView
            ItemsSource= "{StaticResource peopleList}"
            ItemTemplate="{StaticResource treeviewItemStyle}">
        </TreeView>
    </Grid>
</Window>




当然,你可以用ObjectDataProvider来做数据提供者,使用ObservableCollection和INotifyPropertyChanged来通知UI刷新

TOP

发新话题