I have a custom user control in XAML that creates a ItemsControl which ItemsPanel is a 15 * 15 uniform grid. The ItemsControl is then populated with Cells on startup.
<UserControl x:Class="Words.GameBoard"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:Words="clr-namespace:Words"
xmlns:Cell="Words.CellCollection"
xmlns:CellTile="Words.Cell"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<Words:CellCollection x:Key="CellCollectionData">
</Words:CellCollection>
<Style TargetType="ItemsControl">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<UniformGrid IsItemsHost="True" Margin="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Words:Cell>
</Words:Cell>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<ItemsControl Name="BoardControl">
</ItemsControl>
The control is added to the MainWindow like this
<clr:GameBoard>
</clr:GameBoard>
How do i bind the Items of a ItemsControl to a Array? I don’t need Observables and stuff, I just want the Items to refresh when I click a button. Is this possible? I’ve very new to both C# and XAML
Thanks
You need to set the ItemsSource on your ItemsControl to bind the array like this:
I am assuming you wanted the CellCollectionData bound. Typically, however, I would expect the data to be in the DataContext, in which case you would use:
(if the UserControl’s DataContext was set to the array)
or
(if the UserControl’s DataContext was a class that contained a property that returned the array)
While you are learning and testing, I would suggest converting the ItemsControl to a ListBox, so you can see that items are actually added (by clicking on a selectable item). Once you get the look right, you can change it back to an ItemsControl (which doesn’t allow selecting an item).