WPF UserControl with generic code-behind

后端 未结 3 823
余生分开走
余生分开走 2020-12-31 05:49

I have this code behind:

CustomUserControl.xaml.cs

namespace MyProject
{
    public partial class CustomUserControl : UserControl
    {
             


        
3条回答
  •  时光说笑
    2020-12-31 06:11

    Haven't found my solution anywhere else so far. The main difference is, that I have got one .xaml file for the generic user control class and not one for each actual user control.

    GenericUserControl.xaml.cs

    using System.Windows.Controls;
    
    namespace TestGenericUserControl
    {
        public abstract partial class GenericUserControl : UserControl
        {
            // If you use event handlers in GenericUserControl.xaml, you have to define 
            // them here as abstract and implement them in the generic class below, e.g.:
    
            // abstract protected void MouseClick(object sender, MouseButtonEventArgs e);
        }
    
        public class GenericUserControl : GenericUserControl
        {
            // generic properties and stuff
    
            public GenericUserControl()
            {
                InitializeComponent();
            }
        }
    
        // To use the GenericUserControl in XAML, you could define:
        public class GenericUserControlString : GenericUserControl { }
        // and use it in XAML, e.g.:
        // 
        // alternatively you could probably (not sure) define a markup extension to instantiate
        // it directly in XAML
    }
    

    GenericUserControl.xaml

    
        
            
    
    

提交回复
热议问题