WPF和ObservableCollection <t> </t>

时间:2013-03-29 02:31:57

标签: c# .net wpf observablecollection

我想要显示ObservableCollection<IRuleCondition> - IRuleCondition接口由我想要显示的2个不同的类使用,RuleCondition只显示一个规则条件(信息等)作为优先级,要检查的属性等,以及RuleConditionGroup,可以包含2个或更多RuleConditions,按照任何条件可以匹配的方式进行分组,或者等等。

在XAML中我想知道有没有办法显示不同的ListView.ItemTemplate,具体取决于它在ObservableCollection<IRuleCondition>中遇到的类型?或者我需要实现两个不同的ObservableCollection s?

3 个答案:

答案 0 :(得分:9)

以下是一个如何运作的简单示例

这是对象的定义方式

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代码

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

<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

enter image description here

这就是糟糕输出的样子。请注意,与经理相比,员工显示的绿色和红色背景和额外字段

答案 1 :(得分:2)

只需在参考资料部分定义两个不同的DataTemplates,每个RuleCondition类型一个。

答案 2 :(得分:1)

1)创建两个不同的数据模板,就像您说的那样。 2)创建自定义DataTemplateSelector以选择适当的模板。

您的一条评论声明您从DataTemplateSelector收到错误。验证您是否正确实现了类,也许粘贴您的实现。它应该相当小而且直截了当。

相关问题