Jake
Jake

Reputation: 11430

How to set WPF default values for properties, if possible?

I am just starting WPF and it is frustrating the hell out of me. It seems that many properties are null by default (at least those I am working on at the moment) and hence when it compiles and run, nothing happens.

Is there a quick way or a standard workflow procedure to set default values for WPF objects?

For example, I put a Canvas and a Button in XAML view, and then went to code view to add an event handler on the Button to Canvas.Children.Add(new Ellipse()) and then nothing happens. Then I thought maybe I should specify the Width and Height. Still nothing happens. Finally, after much struggling I found the Shape.Stroke property.

Then there is no intuitive Ellipse.X and Ellipse.Y to position the Ellipse. Again, took an hour to find the Canvas.SetLeft().

The final straw is when I try to do Canvas.SetLeft(Random.Next(0, (int)Canvas.Width)); It give a runtime error because Canvas.Width is NULL?!!? Goodness...

Sure, WPF gives a lot of features, but seems like a lot of work coming from a Winforms Graphics.DrawEllipse() .. *sweat*

Upvotes: 2

Views: 3653

Answers (2)

sa_ddam213
sa_ddam213

Reputation: 43596

In WPF if you dont explicitly set the Width/Height in xaml the size will be determined by the Elements layout Container, so to access the Width/Height of an Element like this you use the properties ActualWidth/Actualheight, these return the Rendered size of the Element

Example:

Canvas.SetLeft(Random.Next(0, (int)Canvas.ActualWidth));

If you want to create Default values for a Element you can create a style in xaml for that Element

Example:

<Style TargetType="Ellipse">
    <Setter Property="Stroke" Value="Black"/>
</Style>

Upvotes: 2

cunningdave
cunningdave

Reputation: 1480

WPF does have a rough learning curve. One of the tougher things is to dispense somewhat with the techniques you may be used to and embrace the WPF-approach. Xaml is the way to go for defining controls and their properties - Xaml is a language whose only real purpose to do declaration well. In essence, think of the Xaml portion of your code as a glorified constructor.

<Window x:Class="TestWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="Window"
        Title="MainWindow"
        Width="640"
        Height="480">       
    <Canvas>
        <Ellipse Canvas.Left="50"
                 Canvas.Top="50"
                 Width="142"
                 Height="88"
                 Fill="Black" />
    </Canvas>
</Window>

The declaration above takes advantage of Xaml's nifty syntax for Attached Properties.

You might want to investigate Styles if you find yourself setting a set of common properties on like objects often.

Upvotes: 1

Related Questions