Creating controls dynamically using xaml

霸气de小男生 提交于 2021-01-28 04:21:27

问题


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);

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?

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

List = new List where MyRules is

String Name; String Condition;

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


回答1:


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>


来源:https://stackoverflow.com/questions/28087773/creating-controls-dynamically-using-xaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!