I would probably suggest using an MVVM approach. Just set the DataContext
property of the window and then bind the ItemsControl.ItemsSource
property to the list you want, e.g. ItemsSource="{Binding MyItemsListProperty}"
.
A full example of what this could look like (based on the example code you posted above):
$xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="MainWindow"
Title="ItemsControlDataBindingSample" Height="350" Width="300">
<Grid Margin="10">
<ItemsControl ItemsSource="{Binding MyItemsListProperty}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Title}" />
<ProgressBar Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding Completion}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
"@
[void][System.Reflection.Assembly]::LoadWithPartialName('PresentationFramework')
#Read XAML
$window = [Windows.Markup.XamlReader]::Parse($xaml)
$viewModel = New-Object PSObject -Property @{
MyItemsListProperty = @(
New-Object PSObject -Property @{
Title='Complete this WPF tutorial'
Completion=45.0
};
New-Object PSObject -Property @{
Title='Learn C#'
Completion=80.0
};
New-Object PSObject -Property @{
Title='Wash the car'
Completion=25.0
};
New-Object PSObject -Property @{
Title='Make KIDS do homework'
Completion=3.0
};
)
};
$window.DataContext = $viewModel
$window.ShowDialog()