有没有什么好教您如何创建WPF控件完全在运行时?
Is there any good tutorial for creating WPF controls entirely at runtime?
感谢
有没有这样的教程中,我知道了,部分原因是因为这是很简单的,如果你已经得到了控制已经在你的XAML定义。
There is no such a tutorial I know of, partially because that is quite straightforward if you've got already your XAML definition for the control.
之间的XAML code和相应的C#code的对应关系是简单。
The correspondence between XAML code and corresponding C# code is simple.
例如:
<Button Height="80" Width="150">Test</Button>
进入
Button button = new Button() { Height = 80, Width = 150, Content = "Test" };
parentControl.Add(button);
的事情你应该知道的:
内容模型:哪里的内容(开始和结束标记之间的code)去?它可以是财产内容
(如按钮
的情况下),或一组子项(如案例电网
)的。
在XAML有时特殊的价值转换器,隐式应用;在C#code,你必须自己做。例如:
Content model: where does the content (the code between the opening and closing tags) go? It can be either property Content
(as in Button
's case), or a set of child items (as in case of Grid
).
In XAML sometimes special value converters are implicitly applied; in C# code you must do it yourself. Example:
<Button Margin="1, 2"/>
变成
Button button = new Button() { Margin = new Thickness(1, 2, 1, 2) };
每个UI元素只能有一个父元素。也就是说,你可以不一样的元素添加到两个不同的父母作为孩子。
Each UI element can have only one parent element. That is, you cannot add the same element to two different parents as a child.
绑定在一个非常特殊的方式定义的:
Bindings are defined in a quite peculiar way:
<Label MaxWidth={Binding ActualWidth, Source={Binding ElementName=Container}}>
进入
Label label = new Label();
label.SetBinding(
Label.MaxWidthProperty,
new Binding("ActualWidth") { Source = Container }
);
(最好是引用容器
依不是名称实际参考)。
(it's better to reference the Container
by actual reference than by name).
的语法附加属性又是并不简单:
The syntax for attached properties is again not straightforward:
<Label Grid.Column="1"/>
变成
Label label = new Label();
Grid.SetColumn(label, 1);
请注意,每个构造/属性,你可以看一下MSDN中的前preSS它在这两个XAML和C#的具体的方式,通常是直接在文章描述你正在寻找的概念。
Please note that for each of the constructs/attributes you can look up in MSDN the exact way to express it in both XAML and C#, usually directly at the article describing the concept you are looking for.