开发者

WPF runtime control creation

Is there any good tut开发者_Python百科orial for creating WPF controls entirely at runtime?

Thanks


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.

The correspondence between XAML code and corresponding C# code is simple.

Example:

<Button Height="80" Width="150">Test</Button>

gets into

Button button = new Button() { Height = 80, Width = 150, Content = "Test" };
parentControl.Add(button);

The things you should know:

  1. 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).
  2. In XAML sometimes special value converters are implicitly applied; in C# code you must do it yourself. Example:

    <Button Margin="1, 2"/>
    

    turns into

    Button button = new Button() { Margin = new Thickness(1, 2, 1, 2) };
    
  3. Each UI element can have only one parent element. That is, you cannot add the same element to two different parents as a child.

  4. Bindings are defined in a quite peculiar way:

    <Label MaxWidth={Binding ActualWidth, Source={Binding ElementName=Container}}>
    

    gets into

    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).

  5. The syntax for attached properties is again not straightforward:

    <Label Grid.Column="1"/>
    

    turns into

    Label label = new Label();
    Grid.SetColumn(label, 1);
    

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜