I do have two problems regarding custom controls:
I created a custom UserControl
public partial class MyControl : UserControl
{
public static DependencyProperty ControlProperty = DependencyProperty.Register("Control", typeof(UIElement), typeof(MyControl ), null);
public UIElement Control
{
get { return GetValue(ControlProperty) as UIElement; }
set { SetValue(ControlProperty,value); }
}
}
Now I want to embed any “regular” control into my control using XAML
<Grid>
<own:MyControl>
<own:MyControl.Control>
<TextBox x:Name="txtTest" />
</own:MyControl.Control>
</own:MyControl>
</Grid>
1) When trying to access the TextBox by its name in code-behind I just can’t because it is null. What might the problem be? If I would place the same TextBox just inside the Grid the name would resolve to the instance as it should.
2) I can’t find my class using the VisualTreeHelper. The GetChild method just pretends my control isn’t there. Why does this happen?
Thank you in advance!
VisualTreeHelper isn’t “pretending” at all. The value of the
MyControl.Controlproperty is not in the Visual Tree. Just being present in the Xaml does not mean it will be added to the visual tree.Only when the control is added as a child of UI Element that is already in the Visual Tree such as a Panel, a ContentControl or a Border will it also become part of the visual tree.
You could do this:-
In code-behind:-
Probably isn’t what you are trying to do, so what is it you are trying to do?