views:

38

answers:

3

Hi,

I have just started using WPF. I'm getting my head around styling system since. I come from a CSS background and I would like to set margin in percentage.

    <Style TargetType="TextBlock" x:Key="workflowNameTextBlock">            
        <Setter Property="Margin" Value="50"/>            
    </Style>

Currently value is set in pixels, but I would like to set it in %, i.e. 50%.

How can I achive this?

Thank you

A: 

You can't set the Margin in percentage.

You can attach handler for the SizeChanged event and do it manually.

Or you can create a Converter and bind to the Width

Svetlozar Angelov
Thank you for reply. In regards to converter. I'd have to calculate width of the parent object and then use that value/2 in order to get a 50% margin. Do you know if there is a reason why it's implemented in such a way?
vikp
It's implemented that way because the WPF layout engine doesn't render the way CSS does. It uses the `Grid` for proportional layout, not the `Margin`. So if you're bent on using `Margin` for positioning, you'll need to implement that functionality yourself.
Robert Rossney
+3  A: 

Instead of using Margin, you can do this via a Grid.

Just place your control within a Grid element, and use 3 columns and 3 rows. The column/row sizing can be done as percentages of the containing element.

Reed Copsey
+2  A: 

Here's how you implement 20% left and right margins in WPF:

<Grid>
   <Grid.ColumnDefinitions>
      <ColumnDefinition Width="2*"/>
      <ColumnDefinition Width="6*"/>
      <ColumnDefinition Width="2*"/>
   </Grid.ColumnDefinitions>
   <TextBlock Grid.Column="1" Text="Hello, world."/>
</Grid>

This may seem ridiculously verbose if what you're trying to do is re-implement a simple CSS layout in WPF, but that's because implementing simple CSS layouts is really not the problem space WPF is designed around.

Robert Rossney