WPF ItemControl:将项目的类型限制为特定类型
我正在创建一个 WPF 自定义控件来作为练习,以在 VS 面板中显示日志消息(错误/警告/消息)。该控件是一个 ItemControl,每个项目都是要显示的消息。但我必须将消息分类到正确的类别中,因此我需要每个项目公开一些内容(可能是一个接口),以便让控件知道如何对消息进行分类。我不知道如何强制 Item 为某种类型,我怎样才能实现这一点? 设计策略是否错误? 谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以从 ItemsControl 继承自定义控件并创建强类型集合属性,然后在控件的模板中添加以下行:
我经常使用 ObservableCollections。
使用 ItemsControl 的事实并不要求您直接使用其 ItemsSource,您可以改为绑定到它。
PS 从技术上讲,任何人仍然有可能绕过 MyStronglyTypedCollectionalPropertyName 直接设置 ItemsSource。就我个人而言,我认为在这种情况下抛出不是一个好主意,但您可以从 OnPropertyChanged 中检查值类型:
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:
I do it a lot with ObservableCollections.
The fact that you use ItemsControl doesn't oblige you to use its ItemsSource directly, you can bind to it instead.
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: