Your example doesnt look like MVVM, but if u want to have data in your code behind -- do it with dependency propertys.
Here is the example for the XAML
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
Name="myWindow">
<Grid>
<ListView ItemsSource="{Binding ElementName=myWindow, Path=DrawingVisualCollection}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"></GridViewColumn>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Path=Id}"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
The code behind looks like this
namespace Test
{
public class DrawingVisualObject : DrawingVisual
{
public int Id { get; set; }
public string Name { get; set; }
public DrawingVisualObject(int id, string name)
{
Id = id;
Name = name;
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<DrawingVisualObject> DrawingVisualCollection
{
get { return (ObservableCollection<DrawingVisualObject>)GetValue(DrawingVisualCollectionProperty); }
set { SetValue(DrawingVisualCollectionProperty, value); }
}
// Using a DependencyProperty as the backing store for DrawingVisualCollection. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DrawingVisualCollectionProperty =
DependencyProperty.Register("DrawingVisualCollection", typeof(ObservableCollection<DrawingVisualObject>), typeof(MainWindow), new PropertyMetadata(new ObservableCollection<DrawingVisualObject>()));
public MainWindow()
{
InitializeComponent();
List<DrawingVisualObject> sample = new List<DrawingVisualObject>();
sample.Add(new DrawingVisualObject(1, "Yolo"));
sample.Add(new DrawingVisualObject(2, "Swag"));
this.FillCollection(sample);
}
public void FillCollection(IEnumerable<DrawingVisualObject> objects2fill)
{
this.DrawingVisualCollection.Clear();
foreach(DrawingVisualObject obj in objects2fill)
{
this.DrawingVisualCollection.Add(obj);
}
}
}
}
This should work for you
Keep in mind:
if u are initializing the Collection again, you may destroy the binding. I tried to show this at the example method FillCollection(). So this means if you are using MVVM you should allways set your ObservableCollection to private set.
I recommend you drop in at MVVM again more exactly. To know what is the common base for viewmodels is allways a good start!!!