我在这里发表了一篇关于一些非常相似的博客文章;
http://pjgcreations.blogspot.co.uk/2013/03/wpf-programmatically-adding-buttons.html
下面使用 Canvas、ItemPresenter 和 DataTemplate 来显示在运行时从 ViewModel 填充的按钮。
XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Canvas x:Name="MyCanvas">
<ItemsControl ItemsSource="{Binding MyButtons}" Height="237" Width="507">
<ItemsControl.ItemsPanel >
<ItemsPanelTemplate>
<Canvas IsItemsHost="true"></Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Margin="{Binding ControlMargin}" Content="{Binding Content}" Command="{Binding DataContext.ButtonCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" CommandParameter="{Binding ProductId}"></Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Canvas>
</Window>
流体按钮类;
Public Class FluidButton
Public Property Content As String
Public Property LeftPos As Double
Public Property TopPos As Double
Public Property ProductId As Double
'Returns the Control Margin, using the Class Properties
Public ReadOnly Property ControlMargin As Thickness
Get
Return New Thickness With {.Left = LeftPos, .Top = TopPos}
End Get
End Property
End Class
ViewModel 中的属性;
'Our Collection of Buttons or Products
Public Property MyButtons As ObservableCollection(Of FluidButton)
'Used to expose the Button Pressed Execute Commands to the UI for Binding
Public Property ButtonCommand As DelegateCommand
添加一些按钮;
MyButtons = New ObservableCollection(Of FluidButton)
MyButtons.Add(New FluidButton With {.Content = "Test1", .LeftPos = 0, .TopPos = 20, .ProductId = 1})
MyButtons.Add(New FluidButton With {.Content = "Test2", .LeftPos = 40, .TopPos = 30, .ProductId = 2})
MyButtons.Add(New FluidButton With {.Content = "Test3", .LeftPos = 80, .TopPos = 40, .ProductId = 3})
MyButtons.Add(New FluidButton With {.Content = "Test4", .LeftPos = 120, .TopPos = 50, .ProductId = 4})
MyButtons.Add(New FluidButton With {.Content = "Test5", .LeftPos = 160, .TopPos = 60, .ProductId = 5})
我相信您可以轻松修改它以满足您的需求