Adding and changing usercontrol at run time in a WPF application
I have a situation as follows, i am going to use WPF for first time, so any suggestion abt how to proceed whould be great: I hav a drop down, when i select any item from it - it should change the structure of controls in same window. New controls contain - two menu items and a text box and a list box. Selecting one menuitem will display text box and other will show list box. Now for each item in initial combo box i will hav开发者_Go百科e different info for the each menu items.
Problems: Say i have 10 items in combo box - and 2 menu items for each - so 20 different stuff to show. -- How should i declare these 20 different stuffs -- How should i load each when a particular combination is selected
You should look at ControlTemplate. You can define a set of templates, then apply them to a control causing them to be whatever you want them to be. so, when the item changed event fires on your dropdown, load and apply the template that you want.
<!--- your xaml file --->
<Control x:Name="Main"/>
// you CS file....
OnItemChanage(....)
{
if ( Main!= null )
Main.Template = MyNewTemplate;
}
If you want to show multiple sets of controls at once, dd all of the controls to your window and set their Visibility
using a data binding, and use the ComboBox
to update the propertie the controls are bound to.
Or if you only want to show one control at a time, just use a DataContext from the ComboBox:
<Window.DataContext>
<x:Array x:Key="myItems">
<local:Item MenuItem1="abc" MenuItem2="def" />
<local:Item MenuItem1="ghi" MenuItem2="jkl" />
...
<local:Item MenuItem1="ghi" MenuItem2="jkl" />
</x:Array>
</Window.DataContext>
<Grid>
...
<ComboBox x:Name="selection" ItemsSource="{Binding}">
...
<StackPanel DataContext="{Binding /}" ...>
<MenuItem Header="{Binding MenuItem1}" OnClick="DisplayListBox" />
<MenuItem Header="{Binding MenuItem2}" OnClick="DisplayTextBox" />
<TextBox Visibility="Hidden" ... />
<ListBox Visibility="Hidden" ... />
</StackPanel>
</Grid>
with appropriate code for DisplayListBox and DisplayTextBox
精彩评论