且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF和ObservableCollection< T>

更新时间:2022-05-09 08:22:11

这里是一个简单的示例

这是定义对象的方式

public interface Person
{
    string Name { get; set; }
}

public class Manager : Person
{
    public string Name { get; set; }
}

public class Employee : Person
{
    public string Name { get; set; }
    public string ManagerName { get;set;}
}

这是背后的MainWindow代码

This is the MainWindow code behind

public partial class MainWindow : Window
    {
        ObservableCollection<Person> mPeople = new ObservableCollection<Person>();

        public ObservableCollection<Person> People
        {
            get
            {
                return mPeople;
            }
        }

        public MainWindow()
        {
            DataContext = this;
            mPeople.Add( new Employee{ Name = "x" , ManagerName = "foo"});
            mPeople.Add( new Manager { Name = "y"});

            InitializeComponent();
        }
    }

这是MainWindow XAML

This is the MainWindow XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:WpfApplication1"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Window.Resources>
        <DataTemplate  DataType="{x:Type my:Employee}">
            <StackPanel Background="Green" Width="300">
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="{Binding ManagerName}" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate  DataType="{x:Type my:Manager}">
            <StackPanel Background="Red"
                        Width="300">
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>

    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding People}"></ListBox>
    </Grid>
</Window>

如您所见,有两个数据模板,一个用于Manager,一个用于Employee

As you can see there are two datatemplates one for Manager and one for Employee

这就是糟糕的输出的样子.请注意,与经理相比,该员工显示的绿色和红色背景以及多余的字段

And this is how the crappy output looks like. Notice the green and red background and extra field displayed for the Employee compared to the manager