I'm trying to bind a list of elements to my listview, each elements has some propery but i need to bind only following property: Type.
I have read this thread that is very clear but it's not working for me, my listview remains empty... i checked if the list that i bind to listview contains elements and it contains them.
Also i tried to bind a simple "List MyList" and without ListView.ItemTemplate and it works
Following an example of my code, i have this structures:
public class MainType
{
public string Type { get; set;}
}
public class ChildType : MainType
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
public class SimpleClass
{
public ObservableCollection<ChildType> SimpleList { get; set; }
public SimpleClass()
{
SimpleList = new ObservableCollection<ChildType>();
SimpleList.Add(new ChildType { Prop1 = "prop1", Prop2 = "prop2", Type = "type1" }
SimpleList.Add(new ChildType { Prop1 = "prop1", Prop2 = "prop2", Type = "type2" }
}
}
In the source where i have my list view i have this on xaml side:
<ListView x:Name="myListView">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Type}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
and this on C# side:
public sealed partial class MyUserControl : UserControl
{
private SimpleClass MySimpleClass;
public MyUserControl()
{
this.InitializeComponent();
myListView.DataContext = MySimpleClass = new SimpleClass();
myListView.ItemsSource = MySimpleClass.SimpleList;
}
}
Anyone can tell me what i missing?
Thanks!
[EDIT: The above code is correct, the problem was another. ]
The problem was another, inside SimpleClass through another method i deserialize a json file to SimpleList, and it create problems to binding because also if afterwards i simply add an element through ADD method, binding was not working... but if i deserialize the json file to another list: TempList and after through a foreach i add all elements of TempList to SimpleList, it works.
Binding doesn't work:
SimpleList = JsonConvert.DeserializeObject<ObservableCollection<ChildType>>(text, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
Binding works:
TempList = JsonConvert.DeserializeObject<ObservableCollection<ChildType>>(text, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
foreach(ChildType item in TempList)
{
SimpleList.Add(item);
}