2010-01-17 77 views
2

具有以下的WPF代碼的寬度和高度:[WPF]如何設置一個網格數據模板

<Window x:Class="WpfApplication5.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:c="clr-namespace:WpfApplication5" 
Title="Window1" Height="300" Width="300"> 
<Window.Resources> 
    <c:Places x:Key="PlacesData"/> 
    <DataTemplate x:Key="DataTemplate" DataType="{x:Type c:Place}"> 
     <Grid HorizontalAlignment="Left" 
       > 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="*" /> 
       <ColumnDefinition Width="40"/> 
      </Grid.ColumnDefinitions> 
      <TextBlock Grid.Column="0" Text="{Binding Name}"/> 
      <TextBlock Grid.Column="1" Text="{Binding State}" TextAlignment="Right"/> 
     </Grid> 
    </DataTemplate> 
</Window.Resources> 
<Grid> 
    <ListBox ItemsSource="{Binding Source={StaticResource PlacesData}}" 
      ItemTemplate="{StaticResource DataTemplate}" 
      ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
      ScrollViewer.CanContentScroll="False" 
      HorizontalContentAlignment="Stretch"/> 
</Grid> 

輸出是這 alt text http://img51.imageshack.us/img51/3977/listboxscreenshot.jpg

我想狀態碼總是顯示在列表框的右側,如果我調整窗口的大小,這也會發生。

任何想法?

回答

2

確保每個ListBoxItemHorizontalContentAlignment設置爲Stretch

<ListBox> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 
+0

我不工作。同樣的問題 – Alin 2010-01-17 17:53:09

2

讓你的網格的HorizontalAlignmentStretch,不Left

<DataTemplate x:Key="DataTemplate" DataType="{x:Type c:Place}"> 
    <Grid HorizontalAlignment="Stretch"> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="*" /> 
      <ColumnDefinition Width="40"/> 
     </Grid.ColumnDefinitions> 
     <TextBlock Grid.Column="0" Text="{Binding Name}"/> 
     <TextBlock Grid.Column="1" Text="{Binding State}" TextAlignment="Right"/> 
    </Grid> 
</DataTemplate> 
+0

Thx亞當。您的解決方案有效 – Alin 2010-01-17 18:20:09

+3

我的榮幸。雖然我不得不問爲什麼你將其他答案標記爲正確答案:) – 2010-02-18 05:39:22

相關問題