在DataTemplate中绑定Grid.Row / Grid.Column

19
希望这不是重复问题。
我希望能够在XAML中实现以下操作:
<DataTemplate DataType="{x:Type TestApp:ButtonVM}">        
        <Button 
                Grid.Column="{Binding GridColumn}" 
                Grid.Row="{Binding GridRow}" 
                Content="{Binding Path=Info}" 
        />
</DataTemplate>

Content绑定可以正常工作,但Grid.Column和Grid.Row在生成的对象中根本不存在。即使我将它们设置为没有绑定的值(比如Grid.Column="1"),它们也不存在。我使用Snoop查看了应用程序,并发现在我的网格中没有人设置Grid.Column和Grid.Row。

有什么想法吗?


你是如何将ButtonVM对象放入Grid中的?Grid不是一个项控件,因此它不会将任意的视图模型对象作为其子元素。 - Peter Stephens
看下面,我自己成功地完成了它。秘诀是使用ItemsControl.ItemContainerStyle,并在那里使用Setters将绑定注入到模板化的子项中。 - Thorsten79
1个回答

29

在博客的帮助下,我自己解决了这个问题。

据我所知,你不能在内部进行附加属性绑定。

以下方法可以立即解决问题(使用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>

2
啊,没错。应该就是这样了。附加的 Grid.Row 需要成为网格的直接子元素。 - Peter Stephens
我们在这方面遇到了很多问题,尝试了许多其他的解决方案,但只有这个有效!!! - Garvice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接