Visual controls inheritance in WPF
Many companies are building their own base classes wrapping the native UI classes (in order to be able to customize them).
Here a proof-of-concept how you can do Window and UserControl inheritance in WPF.
- The DemoWPFBaseClassesLib : contain the 2 base class for the Window and for the UserControl (both are changing the background color)
public class MyBaseWindow : Window
public class MyBaseUserControl : System.Windows.Controls.UserControl
- The UserControls library DemoWpfBaseClassesUCLibrary with one UserControl derived for the base one
public partial class UserControl1 : MyBaseUserControl
- The standalone WPF application DemoWPFBaseClasses with the main window derived from the base one
public partial class Window1 : MyBaseWindow
There are also changes to do in the XAML files (corresponding to the derived classes) - see the text in yellow:
- For the Window:
<src:MyBaseWindow x:Class="DemoWPFBaseClasses.Window1"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:DemoWPFBaseClassesLib;assembly=DemoWPFBaseClassesLib"
xmlns:my="clr-namespace:DemoWpfBaseClassesUCLibrary;assembly=DemoWpfBaseClassesUCLibrary"
Title="DemoWPFBaseClasses" Height="300" Width="300">
<Grid>
<Button Width="74" Height="24" Content="Test" HorizontalAlignment="Left" Margin="12,12,0,0" VerticalAlignment="Top"></Button>
<my:UserControl1 Width="200" Height="100" HorizontalAlignment="Left" Margin="12,51,0,0" VerticalAlignment="Top"></my:UserControl1>
</Grid>
</src:MyBaseWindow>
- For the UserControl:
<runtime:MyBaseUserControl x:Class="DemoWpfBaseClassesUCLibrary.UserControl1"
xmlns:runtime="clr-namespace:DemoWPFBaseClassesLib;assembly=DemoWPFBaseClassesLib"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
Height="100" Width="200">
<Grid>
<TextBox Height="23" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="120" />
</Grid>
</runtime:MyBaseUserControl>
Comments
- Anonymous
March 19, 2009
PingBack from http://blog.a-foton.ru/index.php/2009/03/19/visual-controls-inheritance-in-wpf/ - Anonymous
March 19, 2009
Thank you for submitting this cool story - Trackback from DotNetShoutout - Anonymous
April 03, 2009
Thanks for the informative example of how to do this in WPF. I've managed to understand how the base classes are working.... Just one question. Is it possible to modify the properties of TextBox1 in any of the other classes besides the user control class?