2016-11-17 67 views
0

我遇到了用戶控制問題。我試圖讓自定義用戶控件填充寬度爲ListBox,即使ListBox使用包含窗口調整大小。WPF用戶控件列表框的填充寬度

現在,作爲WPF的新手(相對來說),我可能會做一些非常錯誤的事情。但我試圖做的是類似如下:

<Window.Resources> 
    <DataTemplate x:Key="CustomControl"> 
     <StackPanel Orientation="Horizontal"> 
      <uc:CustomControl /> 
     </StackPanel> 
    </DataTemplate> 
</Window.Resources> 
<Grid> 
    <ListBox Name="Container" HorizontalAlignment="Stretch" Margin="5,5,5,5" ItemTemplate="{StaticResource CustomControl}" Padding="0" Grid.IsSharedSizeScope="True" UseLayoutRounding="True" /> 
</Grid> 

用戶控件看起來是這樣的:

<UserControl x:Class="CustomControll" 
     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:conv="clr-namespace:DataConverters" 
     mc:Ignorable="d" 
     MinHeight="50" MinWidth="250" Background="#FFACA4A4" Margin="0,5,0,5" HorizontalAlignment="Stretch"> 
<Grid x:Name="CompleteBtn">  
    <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/> 
    <Border BorderBrush="{x:Null}"> 
     <Grid> 
      <TextBlock></TextBlock> 
     </Grid> 
    </Border> 
    <Image Source="img" MouseDown="CompleteBtn_MouseDown" Cursor="Hand" ToolTip="Complete Task" Margin="0,0,10,0" HorizontalAlignment="Right"/> 
</Grid> 

的問題是,這會不會Stretch填補的寬度ListBox

我也嘗試在用戶控件本身上使用Width="{Binding ElementName=Container, Path=ActualWidth}",但這會導致元素比ListBox寬,如果添加了邊距,導致出現水平條。除此之外,如果我添加足夠的這些元素以使垂直滾動條出現,它會稍微覆蓋用戶控件。

因此,我的問題是如何獲得一個用戶控件來填充任何一邊的指定邊距的列表框的寬度(可能會有所不同),而不會出現橫條,並且不會被覆蓋垂直條?

+0

避免StackPanel''在'CustomControl'。 – kurakura88

+0

嘗試定義'ItemsPanelTemplate'。 –

+0

@Lei使用用戶控件時,設置'ItemsPanelTemplate'和定義'DataTemplate'有什麼區別?我的用戶控件不是模板嗎? –

回答

0

簡單的方法:用水平內容對齊=「拉伸」 它應該工作

<Window.Resources> 
    <DataTemplate x:Key="CustomControl"> 

      <loc:UserControl1 /> 

    </DataTemplate> 
</Window.Resources> 
<Grid> 
    <ListBox Name="Container" 
      HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" 
      Margin="5,5,5,5" 
      ItemTemplate="{StaticResource CustomControl}" 
      Padding="0" 
      Grid.IsSharedSizeScope="True" 
      UseLayoutRounding="True" /> 
</Grid> 

讓我知道,如果它不能正常工作。

0
<DataTemplate x:Key="CustomControl"> 
    <Grid> 
     <uc:CustomControl /> 
    <Grid> 
</DataTemplate> 

使用Grid,而不是使用您的DataTemplate