简体   繁体   English

使用XAML动态创建控件

[英]Creating controls dynamically using xaml

I have a list of objects in my application using which I want to create Wrappanels dynamically. 我的应用程序中有一个对象列表,我想使用它们动态创建Wrappanels。 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);

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. 我想用绑定到属性的xaml中的控件创建一个包装面板。 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 例如,我的收藏是

List = new List where MyRules is 列表= MyRules所在的新列表

String Name; 字符串名称; String Condition; 字符串条件;

I want the List Item to be in WrapPanel with TextBox of Name and Condition 我希望列表项位于具有名称和条件的文本框的WrapPanel中

just a code sample for using an ItemsControl. 只是使用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 ). 我假设您使用的是具有这两个属性的对象,并且需要使用ObservableCollection之类的内容,例如@XAMIMAX(在ObservableCollection<MyObject> MyList )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM