Extending user controls in WPF

I created a user control, as usual, from the XAML part and the code part. Now I need to create another user control that shares some functions of the first, but has different views and may also have additional functions in the code.

My first idea was to create an interface for collecting common functions of two types of controls. Is this the right way? And how can I manage the different parts of XAML that I should have? Any advice is appreciated.

+8
wpf user-controls
source share
3 answers

I would like to add one more contribution, which, in my opinion, may be useful for others who are faced with my same situation.

Another possible solution, which, in my opinion, is suitable if the controls you are going to create are not particularly complex, is to create a basic User Control containing the common functions that you want to share: such control will be completely written in C #. In fact, this allows you to inherit user controls consisting of XAML and code. In XAML of an inherited control instead

<UserControl> ... </UserControl> 

You will have

 <MyProject: MyBaseControl x:Class="MyProject.MyExtendedControl"> ... </MyProject: MyBaseControl> 

and then in the code behind you also need to specify the following:

 class MyExtendedControl : MyBaseControl 

Hope this helps.

+9
source share

User controls are not well suited for inheritance in WPF, you can do some hacks to make it work, but in general you will probably be better off using user control. Using this technique is easier to specify different XAMLs for legacy controls. The easiest way to start with a user control is to add a new element to your project like β€œCustom Control (WPF)” and it will add a control and XAML will be added to Themes / generic.xaml for you.

To inherit this control, the easiest way is to add another new user control (WPF) and then change the code behind to inherit from the parent control instead of Control.

+2
source share

There are several ways to separate fragments in order to simplify their work.

MVVM, as pointed out in a comment, relies on data binding to separate logic input controls. By setting the appropriate class that implements INotifyPropertyChanged in the DataContext of your control, you can change the behavior. The DataContext or ViewModel class can implement Visibility properties to show and hide different parts of the input if the differences between them are not too large.

Another way to share functionality is aggregation. See https://stackoverflow.com/a/312960/

You can create smaller controls that implement common functions, and then create larger controls for the intended purpose by combining smaller controls (i.e., aggregating them) to make a larger control. Aggregation will work both for code substitution and data binding.

+2
source share

All Articles