使用 xaml 动态创建控件 [英] Creating controls dynamically using xaml

查看:55
本文介绍了使用 xaml 动态创建控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个对象列表,我想使用这些对象动态创建 Wrappanels.一种方法是在后面的代码中编写控件添加,如下所示.

I have a list of objects in my application using which I want to create Wrappanels dynamically. One way is to write control adding in code behind as below.

WrapPanel RuleInternalCond = new WrapPanel();

// Create operator combo box and fill all operators
ComboBox operatorCb = new ComboBox();
operatorCb.Items.Add("OR");
operatorCb.Items.Add("AND");

RuleInternalCond.Children.Add(operatorCb);

但是有没有更好的方法来创建包装面板的模板,将其绑定到我的属性并使用我在 xaml 中的集合来自动创建包装面板模板列表?

But is there a better way to create a template of the wrap panel, bind it to my properties and use my collection in xaml to create list of wrap panel templates automatically?

详细解释.我想在 xaml 中创建一个带有绑定到属性的控件的包装面板.但是如果我想根据我的收藏动态创建这些包装面板的列表,问题就会出现.例如,我的收藏是

To explain in detail. I want to create an wrap panel with controls in xaml which bind to properties. But the problem comes if I want a list of these wrap panels to be created dynamically depending on my collection. For eg my collect is

列表 = 新列表MyRules 在哪里

List = new List where MyRules is

字符串名称;字符串条件;

String Name; String Condition;

我希望列表项位于 WrapPanel 中,带有名称和条件的文本框

I want the List Item to be in WrapPanel with TextBox of Name and Condition

推荐答案

只是一个使用 ItemsControl 的代码示例.我假设您使用具有这 2 个属性的对象,并且您需要使用像 @XAMIMAX 这样的 ObservableCollection 在评论 (ObservableCollection<MyObject> MyList ) 中写道.

just a code sample for using an ItemsControl. I am assuming you use an object that has those 2 properties and you need to use an ObservableCollection like @XAMIMAX wrote in the comment (ObservableCollection<MyObject> MyList ).

           <ItemsControl ItemsSource="{Binding MyList}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <TextBlock Text="{Binding Name}"/>
                            <TextBlock Text="{Binding Condition}"/>
                        </WrapPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

这篇关于使用 xaml 动态创建控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆