问题
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