简体   繁体   中英

Using C# instead of XAML in Silverlight

Is XAML really necessary? If someone really wanted to, could everything displayed on a Silverlight page be declared at runtime in the C# code? VISIFire has example code where they set up one of their classes, chart, in the C# code and then simply add it to the user interface with a simple C# call:

LayoutRoot.Children.Add(chart);

How would I do a similar creation with a class I already have defined in the XAML file but because of other reasons I need to declare it at runtime? If I could use it as it is in XAML I think it would work because there are no errors with its display. It is declared like this:

        <views:PrescriberPage01 x:Name="DashboardPrescriberPage01" 
    Visibility="Collapsed" SelectedProduct="{Binding SelectedProduct,
 Mode=TwoWay}"Grid.Row ="0"/>

How would I declare that in C# code?

Is XAML really necessary?

I suppose no, you can probably do everything that you can do in XAML in code. But XAML is really, really a much, much more convenient way to go. And I think few would dissagree with this.

How would I declare that in C# code?

You can create bindings in code. Example from MSDN . In your situation it would be something like:

PrescriberPage01 page = new PrescriberPage01();
page.Visibility = Visibility.Collapsed;

Binding myBinding = new Binding("SelectedProduct");
myBinding.Mode = BindingMode.TwoWay;
myBinding.Source = this; // or whatever object carrying the property
                         // "SelectedProduct" that you bind against.

page.SetBinding(PrescriberPage01.SelectedProduct, myBinding);
LayoutRoot.Children.Add(page);

XAML is preferable to describe user interface, in declarative way and I recommend use XAML without code behind and also I would recommend look at MVVM pattern

I would rather say "Is C# really necessary for GUIs when I can use XAML"? XAML is really good and was explicitly design for GUI.

You have two options here. Load your XAML dynamicly .

Or create it in code. (other posted the solution while i was typing AGAIN; ;) )

Simple controls are easy but... you might also want some styling done to those objects + you might want an animation or two... this is already(mostly) provided in xaml... and it is uber easy... If u hate xaml so much you might want to think about "Blend";p

One specific example of something you can't create without Xaml is a DataTemplate.

You can write code which will create a DataTemplate from a XAML string, but you can't add children to a newed up DataTemplate directly in c#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM