2014-09-27 127 views
0

我有一些麻煩,學習WPF中,我已經建立了一個自定義用戶控件,像這樣:如何擺脫此WPF/XAML ListBox填充?

<UserControl 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:local="clr-namespace:LobbyApp" x:Class="LobbyApp.ChatPanel" 
     mc:Ignorable="d" 
     d:DesignHeight="200" d:DesignWidth="600"> 
<UserControl.Resources> 
    <DataTemplate DataType="{x:Type local:ChatMessage}"> 
     <Grid> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition> 
        <ColumnDefinition.Width>Auto</ColumnDefinition.Width> 
        <ColumnDefinition.SharedSizeGroup>Date</ColumnDefinition.SharedSizeGroup> 
       </ColumnDefinition> 
       <ColumnDefinition> 
        <ColumnDefinition.Width>Auto</ColumnDefinition.Width> 
        <ColumnDefinition.SharedSizeGroup>Who</ColumnDefinition.SharedSizeGroup> 
       </ColumnDefinition> 
       <ColumnDefinition> 
        <ColumnDefinition.Width>*</ColumnDefinition.Width> 
       </ColumnDefinition> 
      </Grid.ColumnDefinitions> 
      <DataGridCell BorderThickness="0" Content="{Binding Timestamp}" Grid.Column="0" Background="Black" Foreground="LightCyan"/> 
      <DataGridCell BorderThickness="0" Content="{Binding Who}" Grid.Column="1" Background="Black" Foreground="LightBlue"/> 
      <DataGridCell BorderThickness="0" Grid.Column="2" Background="Black" Foreground="White"> 
       <TextBox Text="{Binding What, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap"/> 
      </DataGridCell> 
     </Grid> 
    </DataTemplate> 
</UserControl.Resources> 

<ListBox ItemsSource="{Binding History}" SnapsToDevicePixels="True" Background="Magenta" Padding="0"/> 

大部分,我覺得無所謂,只是包括它的完整性。有趣的是我看到滾動條外的品紅色背景,就像列表框內容一樣,它的滾動條實際上​​被填充到列表框中。它看起來像這樣:

ListBox Padding

我看即使列表框是一個合理的規模外品紅,它只是更容易看到當你縮小它的小像。

我已經嘗試了每一個我可以擺脫洋紅色的元素的每個邊距/填充,但我似乎無法。我不知道是什麼原因造成的,或者如何「修復」它。我可能會簡化我的例子到最基本的部分,但我認爲我會先發布,因爲也許這只是一個愚蠢的明顯答案。如果是的話,我很抱歉。

回答

0

這是因爲ListBox的邊界填充的硬編碼值爲'1'。

<ControlTemplate TargetType="{x:Type ListBox}"> 
       <Border Name="Bd" 
         Background="{TemplateBinding Background}" 
         BorderBrush="{TemplateBinding BorderBrush}" 
         BorderThickness="{TemplateBinding BorderThickness}" 
         SnapsToDevicePixels="true" 
         Padding="1"> 
        <ScrollViewer Padding="{TemplateBinding Padding}" 
            Focusable="false"> 
         <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> 
        </ScrollViewer> 
       </Border> 
      </ControlTemplate> 

所以,你可以自己修改模板,或者只是破解它象下面這樣:

void OnListBoxLoaded(object sender, RoutedEventArgs e) 
    { 
     Border border = VisualTreeHelper.GetChild((ListBox)sender, 0) as Border; 
     if(border != null) 
     { 
      border.Padding = new Thickness(0); 
     } 
    } 

以上,使您使用Aero主題默認的Windows的假設。如果您更改主題,或者確實如果航空主題發生更改,則可能會中斷。