How do I Access Buttons inside a UserControl from xaml?

后端 未结 6 558
梦如初夏
梦如初夏 2021-01-17 11:51

At work I have several pages, each with buttons in the same places, and with the same properties. Each page also has minor differences. To that end, we created a userControl

6条回答
  •  囚心锁ツ
    2021-01-17 12:28

    rather than use many dependency properties, prefer style approach. Style contains every property available for a Button control.

    I would create a DependencyProperty for each button style in UserControl.

    public partial class TemplateUserControl : UserControl
    {
        public TemplateUserControl()
        {
            InitializeComponent();
        }
    
        public static readonly DependencyProperty FirstButtonStyleProperty = 
            DependencyProperty.Register("FirstButtonStyle", typeof (Style), typeof (TemplateUserControl));
    
        public Style FirstButtonStyle
        {
            get { return (Style)GetValue(FirstButtonStyleProperty); }
            set { SetValue(FirstButtonStyleProperty, value); }
        }
    
        public static readonly DependencyProperty SecondButtonStyleProperty =
            DependencyProperty.Register("SecondButtonStyle", typeof (Style), typeof (TemplateUserControl));
    
        public Style SecondButtonStyle
        {
            get { return (Style)GetValue(SecondButtonStyleProperty); }
            set { SetValue(SecondButtonStyleProperty, value); }
        }
    }
    

    and then modify xaml for buttons to pick these styles:

    
        
            

    now when buttons have to be customized, that can achieved by custom styles:

    
        
            
            
    
            
            
            
    
            
        
    
        
    
    

提交回复
热议问题