2013-07-09 61 views
2

我試圖將wpf中的Dockpanel數據綁定到viewmodel集合。我使用這個來創建一個可自定義的表單,所以我不知道有多少個孩子應該在dockpanel中,直到運行時。Databind DockPanel

我遇到的問題是附加屬性DockStyle.Dock似乎沒有得到應用時,我從數據模板中設置它。以下xaml是我正在做的簡化版本。我期望第一個按鈕填滿屏幕的頂部,但真正發生的是它們是水平堆疊的。即使對DockPanel.Dock屬性進行硬編碼也不會影響按鈕的佈局。當我看看XAMLPad中的可視化樹時,我注意到有ContentPresenters作爲DockPanel的子項而不是按鈕。 ContentPresenter的佈局是否與其他元素不同?有沒有另一種數據綁定到DockPanels的技術?

<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> 

Here is a picture of the rendered control in xamlpad

回答

7

原因未停靠的項目是因爲在DataTemplate控制不是DockPanel的直接孩子。我相信ItemsControl會爲每個項目創建一個ContentPresenter,就像ListBox爲每個項目創建一個ListBoxItem一樣。

您可以嘗試使用ItemContainerStyle停靠控件。我認爲應該在ContentPresenter上設置任何屬性。像這樣的東西可能會奏效:

<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> 

我不知道,如果一個字符串綁定到Dock屬性將工作或沒有,但。您可以嘗試直接使用enum中的值來查看是否也有幫助。

+0

就是這樣!非常感謝幫忙。整個上午我都在爲此而苦苦掙扎。 –

2

這是因爲你的ButtonContentPresenterItemsControl不具有DockPanel.Dock集包裹。嘗試設置ItemContainerStyle到這樣的事情:

<ItemsControl.ItemContainerStyle> 
    <Style TargetType="{x:Type ContentPresenter}"> 
     <Setter Property="DockPanel.Dock" Value="{Binding}"/> 
    </Style> 
</ItemsControl.ItemContainerStyle>