开发者

Access sub-controls of custom control from code

I created a custom control in Expression Blend which consists of multiple TextBlocks placed in a Grid. Now I added this custom control开发者_开发百科 to my phone page in Visual Studio and want to access and change the text of these TextBlocks from C# code.

How do I access these sub-controls in code?

I thought I could do something like this:

MyCustomControl.TextBlock1.Text = "New Text";

But it's not that easy. So how do I do it?


The property MyCustomControl.TextBlock1 exists but is internal, not public. You can use MyCustomControl.FindName("TextBlock1") as TextBlock to locate the resources by name instead.


Does GetTemplateChild(string name); work ? You should be able to use it, to access the elements of your control's template


Try below code both should work for your requirement:

Control subControl1 = (Control)MyCustomControl.Controls[0];

or

TextBox subControl1 = (TextBox)MyCustomControl.Controls[0];

Using any code you are able to access Text Property. Always keep remember the hierarchy in your custom control and then try to access all control level-by-level.

If still you are facing any issue feel free to ask.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜