Silverlight 在WrapPanel中动态创建和绑定按钮

Silverlight 在WrapPanel中动态创建和绑定按钮,silverlight,xaml,Silverlight,Xaml,在此场景中,将向ViewModel发送一组资源 目标是将这些资源显示为视图中包装面板中的按钮 现在,我正在使用下面的C代码来完成这项工作。但是,我希望在Xaml方面这样做。最后,我想使用DataTemplates将按钮与资源类的其他属性一起格式化 最好的方法是什么?提前谢谢 public void SetResources(Resource[] resources) { WrapPanel panel = this.View.ResourcesPanel;

在此场景中,将向ViewModel发送一组资源

目标是将这些资源显示为视图中包装面板中的按钮

现在,我正在使用下面的C代码来完成这项工作。但是,我希望在Xaml方面这样做。最后,我想使用DataTemplates将按钮与资源类的其他属性一起格式化

最好的方法是什么?提前谢谢

    public void SetResources(Resource[] resources)
    {
        WrapPanel panel = this.View.ResourcesPanel;
        panel.Children.Clear();
        foreach(Resource resource in resources)
        {
            var button = new Button
            {
                Tag = resource.Id,
                Content = resource.Content,
                Width = 300,
                Height = 50
            };
            button.Click += this.OnResourceButtonClick;
            panel.Children.Add(button);
        }
    }

显示一组可变项目的常用方法是使用。您可以将ItemsControl的属性绑定到
资源
对象的

<UserControl ...>
    <UserControl.DataContext>
        <local:ViewModel/>
    </UserControl.DataContext>
    <Grid>
        <ItemsControl ItemsSource="{Binding Resources}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Tag="{Binding Id}" Content="{Binding Content}"
                            Width="300" Height="50"
                            Click="OnResourceButtonClick"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</UserControl>

Silverlight中是否有WrapPanel?是的,但您必须在Xaml中添加相应的引用。该引用是什么?xmlns:y=“clr命名空间:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit”太棒了!正是我在寻找的解决方案。非常感谢你。
public class ViewModel
{
    public ViewModel()
    {
        Resources = new ObservableCollection<Resource>();
    }

    public ObservableCollection<Resource> Resources { get; private set; }
}
var vm = DataContext as ViewModel;
vm.Resources.Add(new Resource { Id = 1, Content = "Resource 1" });
...