将自定义/现有FrameworkElements添加到ItemsControl

时间:2013-04-05 20:42:41

标签: wpf datatemplate itemscontrol frameworkelement

当我将覆盖的FrameworkElement或现有的UI控件添加到ItemsControl时,我收到以下绑定错误。

System.Windows.Data Error: 25 : ItemTemplate and ItemTemplateSelector are not valid for item.; Type='Button' System.Windows.Data Error: 25 : ItemTemplate and ItemTemplateSelector are not valid for item.; Type='FrameworkElement'

我应该如何处理混合的UIElement /非UIElement类型到ItemsControl

namespace WpfApplication27
{
    class Data
    {
        public string Type { get; set; }
    };

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

            m_itemsControl.Items.Add(new Data() { Type = "A" });
            m_itemsControl.Items.Add(new Data() { Type = "B" });
            m_itemsControl.Items.Add(new Data() { Type = "A" });
            m_itemsControl.Items.Add(new Button());
            m_itemsControl.Items.Add(new FrameworkElement());
        }
    }

    public class CustomDataTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object _item, DependencyObject _container)
        {
            var container = _container as FrameworkElement;
            var data = _item as Data;

            if (data.Type == "A")
            {
                return container.FindResource("ADataTemplate") as DataTemplate;
            }
            else if (data.Type == "B")
            {
                return container.FindResource("BDataTemplate") as DataTemplate;
            }

            return null;
        }
    }
}

<Window x:Class="WpfApplication27.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication27">

<Window.Resources>
    <DataTemplate x:Key="ADataTemplate">
        <Ellipse Width="5" Height="5" Fill="Red"/>
    </DataTemplate>

    <DataTemplate x:Key="BDataTemplate">
        <Rectangle Width="5" Height="5" Fill="Blue"/>
    </DataTemplate>

</Window.Resources>

    <ItemsControl Name="m_itemsControl">
        <ItemsControl.ItemTemplateSelector>
            <local:CustomDataTemplateSelector/>
        </ItemsControl.ItemTemplateSelector>

        <ItemsControl.Template>
            <ControlTemplate>
                <Canvas IsItemsHost="True"/>
            </ControlTemplate>
        </ItemsControl.Template>
    </ItemsControl>
</Window>

0 个答案:

没有答案