Problem Binding a ObservableCollection to a ListBox in WPF/MVVM
I'm working in some code , using wpf and starting to use mvvm. So far i have no problem, when i have one element and I have to show the values of it in the screen (binding of the specific name of the property). But now, i have to work with a property list , not knowing the names of it. So I created a class, named GClass, that only have two propierties, name and value. I created the ObservableCollection, and fill for now with direct values, and asign the view (lstview) datacontext with the object i have created. But I cant see any result, it always shows a blank listbox. Can someone tell me if see why is happening ?
Code of c#
VDt = new ObservableCollection<GClass>();
var vhDt = message.SelectSingleElement(typeof (Vh)) as Vehiculo;
if(vhDt != null)
{
VDt.Add(new GClass() {Name = "Numero: ", Value = ""});
VDt.Add(new GClass() {Name = "Marca: ", Value = ""});
VDt.Add(new GClass() {Name = "Conductor: ", Value = ""});
lstview.DataContext = this;
开发者_如何学Python _regionManager.RegisterViewWithRegionInIndex(RegionNames.MainRegion, lstview, 0);
Code of the view
<ListBox Margin="5,5,5,25" ItemsSource="{Binding VDt}">
<ListBox.Template>
<ControlTemplate>
<ListViewItem Content="{Binding Name}"></ListViewItem>
<ListViewItem Content="{Binding Value}"></ListViewItem>
</ControlTemplate>
</ListBox.Template>
</ListBox>
I have research here, but i cant see, what I'm doing wrong. I will apreciate if someone help me.
A couple of things here:
Firstly, the <ListBox.Template>
allows you to describe the template for how you wish to draw the listbox itself. What you are trying to do (seemingly) is render the items within the listbox, so you need the <ListBox.ItemTemplate>
Secondly, within the ItemTemplate, you need to create, not a <ControlTemplate>
but rather a <DataTemplate>
Last thing: Personally, I would use fit-for-purpose controls within my DataTemplates to render the views (e.g. TextBlocks
instead of ListViewItems
)
So your xaml should look something like:
<ListBox Margin="5,5,5,25" ItemsSource="{Binding VDt}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Value}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Hope this helps :) Ian
精彩评论