Here I will post problems I and my colleagues met and solutions we found.

Wednesday, March 04, 2009

Fill WrapPanel from the list (WPF)

Sometime, when it is necessary to make a choice from the list, and the list is not that big, it makes sense to use buttons with some actions instead of lists. I found useful technique to do it when the list of actions is dynamic.

The idea is somehow populate WrapPanel with buttons dynamically. We can do it by replacing template for ItemsController.

I lave a collection of elements (it will be assigned to the ItemsSource property in runtime) with Key and Value properties.



<ItemsControl x:Name="activitiesControl" Margin="10">
<ItemsControl.Template>
<ControlTemplate>
<WrapPanel Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"
FlowDirection="LeftToRight" IsItemsHost="true">
</WrapPanel>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Style="{DynamicResource ActionButton}" HorizontalAlignment="Right" Margin="5"
Content="{Binding Value}" Width="200"
Command="{Binding Path=ViewModel.ActionTypeCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=local:CustomerEditView}}"
CommandParameter="{Binding Key}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>


Note that I am using Commands. Finally, we have it. Not in Silverlight yet though.

1 comment:

Unknown said...

Just wanted to say I don't like the command part of the ViewModel pattern. The reason is, the list of possible commands is not available to the view designer. I rather create a list of normal RoutedCommands in the app resource file, bind controls to these commands and bind viewmodel actions programmatically to the same commands.