0

In xaml, with can be set as

<UserControl Width="100" />

I want to set width in VM and bind it to Width in Xaml, like

<UserControl Width="{Binding mywidth}" />

in VM, define mywidth as integer like

public int mywidth {
  get {
      return 100;
  }
}

but it's not working. What kind of type should be set for width binding?

KentZhou
  • 24,805
  • 41
  • 134
  • 200
  • I realize this doesn't answer your question, but I don't think you want width in the ViewModel at all. The ViewModel should control UI state, but should have no knowlege of UI layout. – 17 of 26 Aug 14 '13 at 19:14

1 Answers1

0

I have not experience in WPF, but in silverlight Width and Height values are of type Double. You should not have problems binding it to an integer, however, as silverlight can take care of such things easily. Maybe a description of what you intend to do and what really happen, and a more detailed code sample could help.

EDIT:

That explain all. Width property of a FrameworkElement is a Double type property, but width property of a grid column is a diferent story. Columns of a grid are defined by a collection of ColumnDefinition objects, and their width property is a GridLength type, not a double, since grid column width may take literal numeric values, auto value, and star values (*). However, this is a mere curiosity, since columndefinition class is not derived from framework element, and thus, its properties and not bindable. What you want to do is simply not possible.

You can do it in code, as explained in this question. If you are adamant about using binding, you may try the following workaround:

<Grid HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid  Width="{Binding mywidth}" Grid.Column=1 >
</Grid>

Defining the column as width auto, then placing an element in that column and binding that element width to your property. A column with a width set to Auto have the width of its contents, and thus you can manipulate that column width by manipulating those contents width.

Hope this helps you.

Community
  • 1
  • 1
MACN
  • 196
  • 7
  • 13
  • the binding I am trying is for Grid ColumnDefinition like:. Set property type in VM as either int or double not working. – KentZhou Aug 14 '13 at 18:40