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:
- Content model: where does the content (the code between the opening and closing tags) go? It can be either property Content(as inButton's case), or a set of child items (as in case ofGrid).
- 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) };
- 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}}>- gets into - Label label = new Label(); label.SetBinding( Label.MaxWidthProperty, new Binding("ActualWidth") { Source = Container } );- (it's better to reference the - Containerby actual reference than by name).
- 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.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论