WPF: Custom UserControl that includes a control versus inherits a control

旧时模样 提交于 2020-01-13 18:15:32

问题


I'm creating a UserControl that's a specialized ListBox/View (type not relevant). Now I'm faced with the option to either keep the type as UserControl or Inherit the List control.

1) If I keep it as a UserControl I have a List control inside it and then I have to create a DP for ItemsSource and so on.

2) Let it inherit List control and thus it automatically exposes ItemsSource property.

Is either way acceptable or will it become some Code Horror. What is expected.

Is there maybe a option 3 I'm not aware off?


回答1:


There is no single right answer I'm afraid. The relative merits are:

#1 Hosting a List within a UserControl

PROs

  • It is easier to design this control, i.e. VisualStudio supports UserControls quite nicely
  • You can restrict the interface of the control you are 'extending' for example, if you want to suppress some functionality of the ListView, you can do this by simply not exposing it.

CONs

  • You have to manually expose the functionality of the ListView, by creating your own ItemsSource, ItemTemplate properties etc ... You can however expose the ListView as a property of your UserControl if you like.

#2 Inheriting from ListView

PROs

  • Gives an immediate plug-in replacement if you are replacing existing ListView instances.
  • You do not have to mirror the properties of the ListView.

CONs

  • If you are adding additional controls, you have to create a new template. This can be complex.
  • You cannot easily suppress functionality of the ListView.

So, it really depends on what you want to achieve. Personally I would go for (1) if you want to significantly change the API, for example specialising the ListView for a very specific purpose. I would go for (2) if you are creating a highly generic extension.



来源:https://stackoverflow.com/questions/6201343/wpf-custom-usercontrol-that-includes-a-control-versus-inherits-a-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!