I want to make a wpf user control with list box. in this list box i add a stackpanel as a listbox item.But when i want to use my user control in a application,this user control not showing any data .
here my xaml code of user control
<Grid>
<ListBox x:Name="lb" >
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ContentPresenter/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
i add data in list box like this
StackPanel sp1 = new StackPanel();
sp1.Children.Add(someuielement);// some ui element i generate dynamically
lb.Items.Add(sp1);
my problem is how to show data in main application. i am not using any binding and not able to figure out how to do this.
thanks
The recommended way is to use a view model and bind it to the Items property of the ListBox. Like this:
Then in the codebehind instead of dynamically generating the ui elements you would simply bind your view models to the control, or the parent window.
which may look like this:
See here for a simple
ObservableObject
implementation: http://justinmchase.com/2010/08/26/observableobject-for-wpf-mvvm/