在 WrapPanel 中动态创建和绑定按钮 [英] Creating and binding buttons dynamically in a WrapPanel

查看:49
本文介绍了在 WrapPanel 中动态创建和绑定按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,一组资源被发送到 ViewModel.

In this scenario, an array of resources are sent to the ViewModel.

目标是在视图的 WrapPanel 中将这些资源显示为按钮.

The objective is to display these resources as buttons in a WrapPanel in the view.

此时,我正在使用下面的 C# 代码执行此操作.但是,我想在 Xaml 方面执行此操作.最后,我想使用 DataTemplates 用 Resource 类的其他属性来设置按钮的格式.

At this moment, I'm doing this using the C# code below. However, I'd like to do this in the Xaml side. Eventually, I'd like to use DataTemplates to format the buttons with other properties of the Resource class.

解决这个问题的最佳方法是什么?提前致谢.

What is the best way of approaching this? Thanks in advance.

    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.您将绑定 ItemsControl 的 ItemsSource 属性到 ObservableCollection 你的 Resource 对象.

A common way to display a variable set of items would be to use an ItemsControl. You would bind the ItemsControl's ItemsSource property to an ObservableCollection of your Resource objects.

<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>

ViewModel 类可能如下所示:

The ViewModel class might look like this:

public class ViewModel
{
    public ViewModel()
    {
        Resources = new ObservableCollection<Resource>();
    }

    public ObservableCollection<Resource> Resources { get; private set; }
}

<小时>

您可以通过转换 DataContext 来访问 UserControl 或 MainPage 代码中的 ViewModel 实例:


You may access the ViewModel instance in the UserControl or MainPage code by casting the DataContext:

var vm = DataContext as ViewModel;
vm.Resources.Add(new Resource { Id = 1, Content = "Resource 1" });
...

这篇关于在 WrapPanel 中动态创建和绑定按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆