WPF ItemControl:将项目的类型限制为特定的一种 [英] WPF ItemControl: restrict the type of the item to a specific one

查看:71
本文介绍了WPF ItemControl:将项目的类型限制为特定的一种的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个WPF自定义控件以像在VS面板中一样显示日志消息(错误/警告/消息).该控件是一个ItemControl,每个项目都是要显示的消息.但是我必须将消息分类为适当的类别,因此我需要每个项目都公开一些内容(可能是一个接口),以使控件知道如何对消息进行分类.我不知道如何强制该商品为某种类型,我该如何实现? 设计策略错误吗? 谢谢!

I'm creating as an exercise a WPF custom control to display log messages as in the VS panel (Errors/Warnings/Message). The control is an ItemControl, every item is a message to display. But I have to classify the message in the proper category, so I need each item to expose something ( an interface maybe ) to let the control know how to categorizxe the message. I don't know how to force the Item to be of a certain type, how can I achieve this ? Is the design startegy wrong ? Thanks!

推荐答案

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

you can inherit your custom control from ItemsControl and create a strongly typed collectional property, then in your control's template put the following line:

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

我经常使用ObservableCollections.

I do it a lot with ObservableCollections.

您使用ItemsControl的事实并不意味着您必须直接使用其ItemsSource,而可以将其绑定.

The fact that you use ItemsControl doesn't oblige you to use its ItemsSource directly, you can bind to it instead.

P.S.从技术上讲,这仍然使任何人都可以绕过MyStronglyTypedCollectionalPropertyName直接设置ItemsSource的可能性.就我个人而言,在这种情况下扔它不是一个好主意,但是您可以从OnPropertyChanged中检查值类型:

P.S. Technically speaking that still leaves a possibility for anyone to go off and set ItemsSource directly bypassing MyStronglyTypedCollectionalPropertyName. Personally I don't think that it's a good idea to throw in that case, but you can check the value type from within 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 ItemControl:将项目的类型限制为特定的一种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆