I have a ListView that I want to bind to a list of items (Items), but I want the contents displayed inside TextBlocks.
This is my xaml :
<Window.DataContext>
<local:WindowViewModel/>
</Window.DataContext>
<Canvas Style="{StaticResource MainCanvasStyle}">
<ListView Name="MainListView" Style="{StaticResource MainListViewStyle}" SelectionChanged="ListView_SelectionChanged">
<TextBlock Text="{Binding Items.Number}"/>
<TextBlock Text="{Binding Items.Type}"/>
</ListView>
</Canvas>
And this is my VM :
class WindowViewModel
{
/// <summary>
/// Hides the main window if it's open.
/// </summary>
public ICommand HideWindowCommand
{
get
{
return new DelegateCommand
{
CommandAction = () => Application.Current.MainWindow.Close(),
CanExecuteFunc = () => Application.Current.MainWindow != null
};
}
}
public WindowViewModel()
{
_itemHandler = new ItemHandler();
_itemHandler.Add(new Item("Test1Name", "Test1Type"));
_itemHandler.Add(new Item("Test2Name", "Test2Type"));
}
private readonly ItemHandler _itemHandler;
public List<Item> Items
{
get { return _itemHandler.Items; }
}
}
public class ItemHandler
{
public ItemHandler()
{
Items = new List<Item>();
}
public List<Item> Items { get; private set; }
public void Add(Item item)
{
Items.Add(item);
}
}
public class Item
{
public Item(string number, string type)
{
Number = number;
Type = type;
}
public string Number { get; set; }
public string Type { get; set; }
}
When I launch the program I get an error :
Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
On line
TextBlock Text="{Binding Items.Number}"
but I don't quite understand why.
I'd preferably use a canvas with TextBlocks instead of just plain TextBlocks, but that's another thing I'm not sure how to do.