tags:

views:

14

answers:

2

Hi all. I have several controls which I would like to all share the same width, specified at compile time. So either they all use a width of 10, all use a width of 20, etc.

What is the proper way to define this value once, and use it like a variable from there on out?

"Gives you the idea" pseudocode:

double my_width = 10;
<Label width=my_width content="some text"/>
<Label width=my_width content="some text"/>
<Label width=my_width content="some text"/>
<Label width=my_width content="some text"/>
+1  A: 

Simplest way is in Window's Loaded event, put this code :

this.DataContext = my_width;

and change the markup to :

<Label width="{Binding}" content="some text"/>

--

A better way would be define a static in a class (most possibly your window class) like :

public static Double LabelWidth = 150;

and use it as

<Label Width="{x:Static local:Window1.LabelWidth}" Content="Some Text" />

NOTE: you will have to add an xml namespace reference like :

xmlns:local="clr-namespace:WpfApplication1"

in your window class or wherever you are putting this label.

--

another simple thing to do is create a style :

<Window.Resources>
    <Style x:Key="LabelStyle">
        <Setter Property="Width" Value="100" />
    </Style>
</Window.Resources>

and use it like this :

<Label Style="{StaticResource LabelStyle}" Content="Some Text" />
decyclone
+2  A: 

Hi Adam

Here is a nice little trick I have seen

        <UserControl.Resources> // or wherever it's handy to stick the resource
            <GridLength x:Key="NormalWidth">50</GridLength>
        </UserControl.Resources>

In addition to solving the problem, this lets you separate the width setting from other Style properies you might want to apply (to different label widths). As an added bonus, the GridLength structure supports "*" and "Auto" property for when you want to actually use it for a grid.

Label Width="{StaticResource NormalWidth}"

Cheers,
Berryl

Berryl