我有自定义UserControl。该控件有一个Grid,我可以通过名称访问。但我似乎无法从UserControl的构造函数访问子控件。
我能做到:
this.LayoutRoot
但不是
this.LayoutRoot.MyChildControl
如何以编程方式访问此控件?
答案 0 :(得分:1)
如果您使用了x:Name
属性:x:Name="MyChildControl"
,那么无论嵌套如何,您都会在代码后面引用它。
x:Name
设置FrameworkElement.Name
属性(但也可以用于FrameworkElement
以外的对象)并导致创建一个具有此名称的字段,该字段在{{1}中指定}。
所以你可以简单地打电话:
InitializeComponent()
请注意,this.LayoutRoot...
this.MyChildControl...
有一个FrameworkElement
方法,它的工作方式与预期类似:
FindName
答案 1 :(得分:1)
通过代码,您可以创建UserControl的新对象,然后您可以通过它的名称轻松访问用户控件元素。
MyUserControl ctrl=new MyUserControl();
ctrl.LayoutGrid.Background=new SolidColorBrush(Colors.Blue);
or generally
ctrl.ChildrenName
答案 2 :(得分:0)
用户控件的子控件可以UserControl.Content
访问。如果您想访问Grind的孩子,请使用this.LayoutRoot.Children
。您可以枚举此集合。