从代码访问自定义控件的子控件

发布于 2024-11-02 07:36:04 字数 306 浏览 4 评论 0原文

我在 Expression Blend 中创建了一个自定义控件,它由放置在 Grid 中的多个 TextBlock 组成。现在,我将此自定义控件添加到 Visual Studio 中的手机页面,并希望从 C# 代码访问和更改这些 TextBlock 的文本。

如何在代码中访问这些子控件?

我以为我可以做这样的事情:

MyCustomControl.TextBlock1.Text = "New Text";

但这并不那么容易。那么我该怎么做呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心作怪 2024-11-09 07:36:04

属性 MyCustomControl.TextBlock1 存在,但属于内部,而不是公共。您可以使用 MyCustomControl.FindName("TextBlock1") as TextBlock 按名称查找资源。

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.

橪书 2024-11-09 07:36:04

GetTemplateChild(string name); 有效吗?您应该能够使用它来访问控件模板的元素

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

栀梦 2024-11-09 07:36:04

尝试下面的代码都应该满足您的要求:

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

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

使用您能够访问文本属性的任何代码。
始终记住自定义控件中的层次结构,然后尝试逐级访问所有控件。

如果您仍然遇到任何问题,请随时询问。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文