1

我是 WPF 新手,

问题陈述:我有一个 xml 文件,它给了我需要创建的项目数量,对于每个项目,我需要一个按钮。如果有 20 个项目---> 在加载 xaml 文件时,将读取 xml,将读取并创建计数(项目数)。

有没有办法在 xaml 文件中执行此操作?

4

1 回答 1

3

这是一个简单/快速的解决方法:

在运行时公开一个面板(比如StackPanelXaml并将新按钮添加到它们Children...

MainWindow.xaml:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Loaded="Window_Loaded">

        <StackPanel x:Name="mainPanel"/>

</Window>

主窗口.xaml.cs

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var buttonNames = new List<string>();

            // Parse the XML, Fill the list..
            // Note: You could do it the way you prefer, it is just a sample

            foreach (var buttonName in buttonNames)
            {
                //Create the button
                var newButton = new Button(){Name = buttonName};

                //Add it to the xaml/stackPanel
                this.mainPanel.Children.Add(newButton);    
            }
        }

使用数据绑定的解决方案

MainWindow.xaml:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" >
        <ItemsControl ItemsSource="{Binding YourCollection}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
</Window>

主窗口.xaml.cs

    public MainWindow()
    {
        InitializeComponent();

        YourCollection = new List<Button>();

        // You could parse your XML and update the collection
        // Also implement INotifyPropertyChanged

        //Dummy Data for Demo 
        YourCollection.Add(new Button() { Height = 25, Width = 25 });
        YourCollection.Add(new Button() { Height = 25, Width = 25 });

        this.DataContext = this;

    }

    public List<Button> YourCollection { get; set; }
于 2013-05-02T02:58:58.407 回答