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.
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 StackPanel
s, you could find that your content does not get displayed correctly... I'd advise you to use Grid
s 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:
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.