2010-03-12 81 views
13

希望这不是一个骗局。在DataTemplate中绑定Grid.Row/Grid.Column

我希望能够做到在XAML如下:细

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

内容绑定工作,但Grid.Column和Grid.Row根本就不在生产对象存在。甚至没有将它们设置为一些没有绑定的值时(比如在Grid.Column =“1”中)。我窥探了应用程序,发现在我的网格中没有人设置Grid.Column和Grid.Row。

任何想法?

+0

你是如何让你的ButtonVM对象到Grid?网格不是一个项目控件,因此它不会将任意视图模型对象作为其子项。 – 2010-03-12 13:33:43

+0

见下文,我设法自己做。秘诀是使用ItemsControl.ItemContainerStyle并在那里使用Setters将绑定注入模板化的子级。 – Thorsten79 2010-03-12 13:37:15

回答

18

在博客的帮助下自己解决。

据我了解,你根本不能做附加的属性绑定里面。

下解决了这个问题在瞬间(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> 
+1

啊是的。这应该做到这一点。附加的Grid.Row需要是网格的直接子节点。 – 2010-03-12 17:08:59

+0

我们在这方面有很多问题,并尝试了很多其他解决方案,这是唯一一个工作! – Garvice 2013-03-29 02:18:10