【问题标题】:Adding objects to WPF Panel displaying buttons将对象添加到显示按钮的 WPF 面板
【发布时间】:2017-10-05 07:54:32
【问题描述】:

我想将对象动态添加到 ObservationCollection,然后应该将带有对象字段的内容(值)的按钮添加到面板。

App.xaml.cs 使用 System.Windows;

namespace WpfApp1
{
    public partial class App : Application
    {

    }
}

MainWindow.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ItemsControl Name="dashboardList">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding Name}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>

        </ItemsControl>
    </Grid>
</Window>

DashboadViewModel.cs

using System.Collections.ObjectModel;

namespace WpfApp1
{
    public class DashboardViewModel
    {
        public ObservableCollection<Dashboard> Dashboards { get; set; }

        public DashboardViewModel()
        {
            LoadDashboards();
        }

        public void LoadDashboards()
        {
            ObservableCollection<Dashboard> dashboards = new ObservableCollection<Dashboard>();

            dashboards.Add(new Dashboard { Name = "Dashboard1" });
            dashboards.Add(new Dashboard { Name = "Dashboard2" });

            Dashboards = dashboards;
        }
    }
}

仪表板.cs

namespace WpfApp1
{
    public class Dashboard
    {
        public string Name;
    }
}

如何创建按钮,我是否在使用 ItemControl 的正确轨道上?

【问题讨论】:

    标签: c# wpf xaml panel


    【解决方案1】:

    public string Name 应改为公共属性以支持数据绑定:

    public class Dashboard
    {
        public string Name { get; set; }
    }
    

    除此之外,应将 DashboardViewModel 的实例分配给 Window 的 DataContext 属性,并且 ItemsControl 的 ItemsSource 属性应像这样绑定:

    <Window ...
        xmlns:local="clr-namespace:WpfApp1">
    
        <Window.DataContext>
            <local:DashboardViewModel/>
        </Window.DataContext>
    
        <Grid>
            <ItemsControl ItemsSource="{Binding Dashboards}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Button Content="{Binding Name}" />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Grid>
    </Window>
    

    如果需要,你可以像下面这样在Window的代码中访问视图模型实例:

    var vm = (DashboardViewModel)DataContext;
    vm.LoadDashboards();
    

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 2013-10-27
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      相关资源
      最近更新 更多