WPF ItemsControl : restrict the type of the item to a specific one

标签 wpf itemscontrol

我正在创建一个 WPF 自定义控件作为练习,以在 VS 面板中显示日志消息(错误/警告/消息)。该控件是一个ItemControl,每个项目都是要显示的消息。但是我必须将消息分类到正确的类别中,所以我需要每个项目都暴露一些东西(可能是一个界面),让控件知道如何对消息进行分类。我不知道如何强制 Item 为某种类型,我该如何实现?
设计策略错了吗?
谢谢!

最佳答案

您可以从 ItemsControl 继承您的自定义控件并创建一个强类型的集合属性,然后在您的控件的模板中放入以下行:

<Setter Property="ItemsSource" Value="{Binding MyStronglyTypedCollectionalPropertyName}" />

我经常使用 ObservableCollections。

您使用 ItemsControl 的事实并不要求您直接使用它的 ItemsSource,您可以改为绑定(bind)到它。

附言从技术上讲,任何人仍有可能直接绕过 MyStronglyTypedCollectionalPropertyName 设置 ItemsSource。就我个人而言,我不认为在这种情况下抛出是一个好主意,但您可以从 OnPropertyChanged 中检查值类型:
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgse) 
{   

   if (e.Property == ItemsControl.ItemsSourceProperty && e.NewValue as MySuperTime == null)
   { 

      throw new ArgumentException("ItemsSource value must be of 'MySuperTime' type.");
   }

   base.OnPropertyChanged(e); 

}

关于WPF ItemsControl : restrict the type of the item to a specific one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5139838/

相关文章:

WPF ItemsControl - 如何知道项目何时完成加载,以便我可以关注第一个?

WPF 数据绑定(bind)项目符号列表

wpf - 具有自动垂直滚动功能的多行文本框

c# - 有没有办法在 WPF 控件库中使用 StaticResource 并能够在设计时查看?

.net - 需要更换第 3 方 WinForm 控件,壁橱 WPF 等效项是什么?

wpf - 并排显示的 ItemsControl DataTemplate 项目

c# - 将列表值中的字符串绑定(bind)为 StaticResource

wpf - 使用 WPF 的 F# 事件驱动 MVVM

wpf - ItemsControl 中的 ToggleButtons 绑定(bind)到 ObservableCollection

Silverlight ItemsControl 垂直滚动条,使用包装面板作为 ControlTemplate