WPF ItemControl: restrict the type of the item to

2019-07-07 03:28发布

问题:

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!

回答1:

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}" />

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:

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); 

}