且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何查找在WPF中在运行时中创建的动态控件

更新时间:2023-10-02 09:37:52

我不太了解.您创建了文本框和组合框
在运行时,因此您已经有了对它们的引用(可以将其存储
在您选择的任何方便的数据结构/对象中.
您要达到的目标是什么?
显示一些代码(最多简化为要点)来说明
您的问题.

干杯

曼弗雷德(Manfred)
I don''t quite understand. You created the textboxes and comboboxes
at runtime so you already have a reference to them (that could be stored
in any convenient data structure / object of your choosing).
What is is you''re trying to achieve?
Show some code (simplified to the essentials at best) to illustrate
your issues.

Cheers

Manfred


嗨sivakumarmr10,

您如何添加控件?如果您使用的是WPF,则有可能将"ContentPresenter"绑定到"CodeBehind"文件或"ViewModel"类中的列表,具体取决于您的方法,然后遍历该列表,挑选出您要使用的控件"重新寻找.

您创建的列表可以是您自己的预定义类型的列表,然后此类型可以具有诸如唯一标识符之类的属性.遍历此列表时,可以根据该属性检索所需的控件.

您可以在新创建类型的数据模板中定义控件的类型.

Hi sivakumarmr10,

How are you adding your controls? If you''re using WPF it may be possible to bind a "ContentPresenter" to a List in your "CodeBehind" file or "ViewModel" class, depending on your methodology and then iterate through that list, picking out the control you''re looking for.

The list that you create, could be a list of your own predefined type, this type could then have a property such as unique identifier. When iterating through this list, you could retrieve the control that you need depending on that attribute.

You can define the type of control inside a data-template of your newly created type.

<DataTemplate DataType="{x:Type MyClass}">
    <Button/>
<<DataTemplate />



然后在您的XML文件中:



Then in your XML file :

<Border BorderThickness="1" Background="White">
    <ScrollViewer>
        <ItemsControl ItemsSource="{Binding MyClassDP}" />
    </ScrollViewer>
</Border>



然后,根据后面代码的数据上下文,您可能希望在后面的代码中或单独的类中设置依赖项属性,以不使用.xaml.cs文件:



Depending on the data context of your code behind you may then wish to set a dependency property in either the code behind or a separate class, naive to your .xaml.cs file :

#region MyClassDp
/// <summary>
/// MyClassDp Dependency Property
/// </summary>
public static readonly DependencyProperty MyClassDpProperty =
    DependencyProperty.Register("MyClassDp", typeof(List<MyClass>), typeof(Program),
        new FrameworkPropertyMetadata((List<MyClass>)null));
/// <summary>
/// Gets or sets the MyClassDp property. This dependency property
/// indicates a list of my custom class.
/// </summary>
public List<MyClass> MyClassDp
{
    get { return (List<MyClass>)GetValue(MyClassDpProperty); }
    set { SetValue(MyClassDpProperty, value); }
}
#endregion




我希望这会有所帮助,如果这不是您要采用的方法,则深表歉意.对于WPF数据绑定,我在其他地方也对此给出了类似的答案,这可能会有所帮助.

将DP自动生成的代码片段归功于 DR WPF .




I hope this helps, apologies if that''s not the approach you''re going for. I have given a similar answer to this one elsewhere in relation to WPF data-bindings which might help.

Credit to DR WPF for DP Auto-Generated Snippet.