2

我正在尝试将 wpf 中的 Dockpanel 数据绑定到视图模型集合。我正在使用它来创建可自定义的表单,因此在运行时之前我不会知道停靠面板中应该有多少孩子。

我遇到的问题是,当我从数据模板中设置附加属性 DockStyle.Dock 时,它似乎没有被应用。以下 xaml 是我正在做的事情的简化版本。我希望第一个按钮填满屏幕的顶部,但真正发生的是它们水平堆叠。即使硬编码 DockPanel.Dock 属性也不会影响按钮的布局。当我查看 XAMLPad 中的 Visual Tree 时,我注意到有 ContentPresenters 作为 DockPanel 的子项,而不是按钮。ContentPresenters 的布局是否与其他元素不同?是否有另一种技术可以将数据绑定到 DockPanel?

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:sys="clr-namespace:System;assembly=mscorlib" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

<Grid>
<ItemsControl >
         <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <DockPanel LastChildFill="True"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
       <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button DockPanel.Dock="{Binding}" Content="{Binding}"></Button>
            </DataTemplate>
       </ItemsControl.ItemTemplate>
       <sys:String>Top</sys:String>
          <sys:String>Bottom</sys:String>
       <sys:String>Left</sys:String>
       <sys:String>Right</sys:String>
<sys:String>Top</sys:String>
<sys:String>Top</sys:String>
<sys:String>Top</sys:String>
    </ItemsControl>
</Grid></Page>

这是 xamlpad 中呈现的控件的图片

4

2 回答 2

8

The reason that the items aren't docked is because the control in the DataTemplate is not a direct child of the DockPanel. I believe that the ItemsControl creates one ContentPresenter for each item, just like how a ListBox creates one ListBoxItem for each item.

You could try using the ItemContainerStyle to dock the controls. I think that any properties set on it should be set on the ContentPresenter. Something like this might work:

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <DockPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="DockPanel.Dock" Value="{Binding}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
    ...
</ItemsControl>

I'm not sure if binding a string to the Dock property will work or not, though. You might try using the values in the enum directly to see if that helps as well.

于 2013-07-09T19:33:01.503 回答
1

This is because your Button is wrapped by ItemsControl in ContentPresenter which does not have DockPanel.Dock set. Try setting ItemContainerStyle to something like this:

<ItemsControl.ItemContainerStyle>
    <Style TargetType="{x:Type ContentPresenter}">
        <Setter Property="DockPanel.Dock" Value="{Binding}"/>
    </Style>
</ItemsControl.ItemContainerStyle>
于 2013-07-09T19:32:35.113 回答