WPF:从code添加控件 [英] WPF: Add controls from code

查看:119
本文介绍了WPF:从code添加控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经习惯了Windows窗体而不是WPF。因为我认为WPF有我想在我的新项目中使用它很大的优势。

I'm used to Windows Forms but not to WPF. As I think that WPF has great advantages I'm trying to use it in my new projects.

我的问题是下一:
我有一个XML文件巫婆告诉我,我一定要添加到表单控件,但是这个XML可以改变,所以我需要:

My problem is the next: I have an Xml file witch tells me the controls I have to add to a form but this Xml could change so I need to:


  1. 读取XML文件(解决了,没问题)

  2. 创建与我已阅读数据的自定义WPF窗体。

这可能吗?或者我应该使用Windows窗体?

Is it possible? Or should I use Windows Forms?

推荐答案

是的,它是可能的。

WPF提供了无论是在XAML或code创建控件的几种方法。

WPF offers several ways of creating controls either in Xaml or in code.

有关你的情况,如果你需要动态地创建控件,你必须在code来创建它们。你可以创建你的控制,直接使用其构造为:

For your case if you need to dynamically create your controls, you'll have to create them in code. You can either create your control directly using their constructors as in:

        // Create a button.
        Button myButton= new Button();
        // Set properties.
        myButton.Content = "Click Me!";

        // Add created button to a previously created container.
        myStackPanel.Children.Add(myButton);

或者你可以创建你的控件作为一个字符串包含XAML和使用XamlReader来解析字符串,并创建所需的控制:

Or you could create your controls as a string containing xaml and use a XamlReader to parse the string and create the desired control:

        // Create a stringBuilder
        StringBuilder sb = new StringBuilder();

        // use xaml to declare a button as string containing xaml
        sb.Append(@"<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
                            xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
        sb.Append(@"Content='Click Me!' />");

        // Create a button using a XamlReader
        Button myButton = (Button)XamlReader.Parse(sb.ToString());

        // Add created button to previously created container.
        stackPanel.Children.Add(myButton);

现在您要使用这两种方法之一实际上取决于你。

Now for which one of the two methods you want to use really depends on you.

让 - 路易·

这篇关于WPF:从code添加控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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