オーバーライドさ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>