gpt4 book ai didi

c# - 我可以通过字符串引用 WPF 元素吗?

转载 作者:行者123 更新时间:2023-11-30 13:41:21 26 4
gpt4 key购买 nike

我希望能够通过字符串中的文本引用 C# 中的 WPF 元素。像这样:

SelectElementFromString("TestButton").Opacity = 1;

我可以这样做吗?

最佳答案

你真的需要吗?不知怎的,我对此表示怀疑。怎么样:

XAML:


<SomeType Name="_SomeControl" .../>

代码:


_SomeControl.SomeMethod();

以这种方式使用字符串几乎总是一个坏主意,只会使您的代码变得脆弱(我说几乎是因为有一些正当的理由,它们并不常见)。另外,为什么你的方法返回一个字符串?

编辑:根据您在这里的评论,我建议您简单地使用一个集合来遍历您的控件:

I would use that, but it is a pain to go [blah0.Property = true; blah 1.Property = true...] Is there some solution for this that I am missing

几乎每个初级程序员都想这样做(包括几年前的我自己)。创建一组名为 label0 的控件, label1 , label2等,然后像这样循环访问它们:

for( int i = 0; i < numControls; ++i )
{
Control c = GetControl( "label" + i );
}

由于各种原因,这很糟糕,而且(幸运的是)完全没有必要。将所有控件加载到 List<T> 中并根据需要遍历它们。

private List<Whatever> _controls = new List<Whatever>();
private void InitControlList()
{
_controls.Add( someControl );
_controls.Add( someOtherControl );
// and so on. Now just iterate through the list
// when you need to update or access the controls.
}

正如 H.B. 所指出的,我的回答对 OP 有所帮助,但可能无法帮助 future 搜索此论坛但实际上需要直接回答的人。所以,这是 Jon 的回答的转发(谢谢,如果可以的话,我会给你更多的回复 =D)

You can search the child controls of a FrameworkElement with FindName. To set the name for a control, use the Name or x:Name property from XAML.

注意:如果您使用 x:Name,该控件也将在您的 FrameworkElement 的代码隐藏中作为一个字段可用,您将能够直接访问它。

关于c# - 我可以通过字符串引用 WPF 元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5428058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com