wpf - 读取 xml 文件后在 WPF xaml 文件/xaml.cs 文件中动态创建按钮?

标签 wpf xml

我是 WPF 新手,

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

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

最佳答案

这是一个简单/快速的修复:

Xaml中公开一个面板(例如StackPanel),并在运行时将新按钮作为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>

MainWindow.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);    
            }
        }

使用数据绑定(bind)的解决方案

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>

MainWindow.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; }

关于wpf - 读取 xml 文件后在 WPF xaml 文件/xaml.cs 文件中动态创建按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16329584/

相关文章:

wpf - XAML中的点之谜

c# - 当值设置回有效值时,ValidationRules 不会消除错误

wpf - 两种方式 wpf datagrid 绑定(bind)到数据库

python - 在 python 中使用 argparse 将 csv 转换为 xml

Java - XML 到 JSON 转换(org.json.JSONException : Mismatched meta and head at character 573 )

xml - Coldfusion - XML 格式化从 API 调用返回的字符串

c# - WPF Storyboard 动画不闪烁

c# - 如何使用 ComboBox SelectionChanged 事件更改 StackPanel 颜色?

Python,在已知字符串正下方的行中搜索文本?

xml - 如何在 Android 的 TableLayout 中设置表格宽度和列数