19

Hope this is not a dupe.

I would like to be able to do the following in XAML:

<DataTemplate DataType="{x:Type TestApp:ButtonVM}">        
        <Button 
                Grid.Column="{Binding GridColumn}" 
                Grid.Row="{Binding GridRow}" 
                Content="{Binding Path=Info}" 
        />
</DataTemplate>

The Content binding works fine but Grid.Column and Grid.Row simply don't exist in the produced object. Not even when I set them to some value without binding (like in Grid.Column="1"). I've snooped the application and saw that inside my grid nobody ever sets Grid.Column and Grid.Row.

Any ideas?

Thorsten79
  • 10,038
  • 6
  • 38
  • 54
  • How are you getting your ButtonVM objects into the Grid? The Grid isn't an items control and so it won't take arbitrary view-model objects as its children. – Peter Stephens Mar 12 '10 at 13:33
  • See below, I managed to do it myself. The secret is to use ItemsControl.ItemContainerStyle and use Setters there to inject the binding into the templated child. – Thorsten79 Mar 12 '10 at 13:37

1 Answers1

29

Solved it myself with help from the blogs.

As far as I understand you simply can't do the attached property binding inside.

The following solves the problem in an instant (ItemContainerStyle!):

<DataTemplate DataType="{x:Type TestApp:GridVM}">
        <ItemsControl ItemsSource="{Binding Path=Children}">
            <ItemsControl.ItemContainerStyle>
                <Style>
                    <Setter Property="Grid.Row" Value="{Binding GridRow}" />
                    <Setter Property="Grid.Column" Value="{Binding GridColumn}" />
                </Style>
            </ItemsControl.ItemContainerStyle>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Grid ShowGridLines="True"  Style="{Binding Path=Style}">
                        <Grid.RowDefinitions>
                            <RowDefinition Height=".5*" />
                            <RowDefinition Height=".5*" />                            
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width=".5*" />
                            <ColumnDefinition Width=".5*" />
                        </Grid.ColumnDefinitions>                        
                    </Grid>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
</DataTemplate>
Thorsten79
  • 10,038
  • 6
  • 38
  • 54
  • 2
    Ah yes. That should do it. The attached Grid.Row needs to be an immediate child of the grid. – Peter Stephens Mar 12 '10 at 17:08
  • We were having lots of issues around this and have tried many other solutions out there and this was the only one that worked!!! – Garvice Mar 29 '13 at 02:18