How to add controls dynamically to a UserControl through user's XAML?

后端 未结 1 1563
暗喜
暗喜 2021-01-18 21:09

I want to create a user control that contains a TextBlock and a StackPanel that will allow the user to add his/her own controls to the user control dynamically in XAML.

1条回答
  •  走了就别回头了
    2021-01-18 21:54

    You can do that, although not quite like your example. You need two things. The first is to declare a DependencyProperty of type UIElement, of which all controls extend:

    public static DependencyProperty InnerContentProperty = DependencyProperty.Register("InnerContent", typeof(UIElement), typeof(YourControl));
    
    public UIElement InnerContent
    {
        get { return (UIElement)GetValue(InnerContentProperty); }
        set { SetValue(InnerContentProperty, value); }
    }
    

    The second is to declare a ContentControl in the XAML where you want the content to appear:

    
        
        
            
        
    
    

    In my opinion, if you use StackPanels, you could find that your content does not get displayed correctly... I'd advise you to use Grids for layout purposes for all but the simplest layout tasks.

    Now the one difference to your example is in how you would use your control. The InnerContent property is of type UIElement, which means that it can hold one UIElement. This means that you need to use a container element to display more than one item, but it has the same end result:

    
        
            
                

    And the result:

    enter image description here


    UPDATE >>>

    For the record, I know exactly what you want to do. You, it seems, do not understand what I am saying, so I'll try to explain it one last time for you. Add a Button with the Tag property set as I've already shown you:

    Now add a Click handler:

    private void ButtonClick(object sender, RoutedEventArgs e)
    {
        Button button = (Button)sender;
        if (button.Tag = "MyButton1") DoSomething();
    }
    

    That's all there is to it.

    0 讨论(0)
提交回复
热议问题