2011-03-12 9 views
0

사용자 지정 속성 인 ListViewcolumns.Stretch를 확장하는 ListView 상자를 사용하고 있습니다. 이것은 3 개의 열을 가질 수 있기 때문에 창 크기에 상관없이 고르게 배치됩니다. 내 문제는 목록보기 항목의 끝 부분에있는 "잘라 내기"입니다ListView에서 항목 잘라 내기 방지하는 방법

그래서 내 목록보기에 빨강, 녹색 및 검정의 3 개 항목이 포함되어 있습니다. 항목을 삽입하면 항목이 적절한 열에 삽입되고 다른 두 열 빈 텍스트를 삽입합니다. 0 위치에 항목을 삽입하여 항상 위쪽에 표시하고 나머지는 모두 내립니다. 스크롤 막대는 기본적으로 해제되어 있습니다.

- 목표는 창의 크기 또는 크기에 관계없이 3 개의 열이 전체 창 공간을 차지하도록하고 텍스트의 크기를 적절하게 조정합니다 (최대 높이 : 100-150). 그리고 행이 전체 콜렉션을 채울 때, 맨 아래 행은 뷰 밖으로 "스팬"할 수 없으며, 뷰에 모두 있거나보기에 없음이어야합니다.

어쨌든 - 코드. 어떤 도움 내 목표 모니터에서 작동하지만 이상적으로 나는 그것이 적절하게

ListView에

<ListView Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Transparent" Margin="15,10,5,5" 
         FontFamily="Impact" FontWeight="Bold" BorderThickness="0" VerticalContentAlignment="Stretch" 
        ScrollViewer.VerticalScrollBarVisibility="{Binding VerticleScrollVisibility}" ScrollViewer.HorizontalScrollBarVisibility="Auto" 
        ItemsSource="{Binding PlayNumbers}" 
        ItemContainerStyle="{StaticResource ListViewStyle}" ext:ListViewColumns.Stretch="True"> 
       <ListView.View> 
        <GridView> 
         <GridView.ColumnHeaderContainerStyle> 
          <Style> 
           <Setter Property="FrameworkElement.Visibility" Value="Collapsed" /> 
          </Style> 
         </GridView.ColumnHeaderContainerStyle> 
         <GridView.Columns> 
         <GridViewColumn Header="Red" CellTemplate="{StaticResource RedItemTemplate}" /> 
          <GridViewColumn Header="Green" CellTemplate="{StaticResource GreenItemTemplate}" /> 
          <GridViewColumn Header="Black" CellTemplate="{StaticResource BlackItemTemplate}" /> 
         </GridView.Columns> 
        </GridView> 
       </ListView.View> 
    </ListView> 

의 크기를 조정하려면 완벽한 크기를 찾을 때까지 열심히 뷰 박스의 최대 높이를 코딩 할 수 주시면 감사하겠습니다 스킨 파일

<!--  Templates for Number ListBox   --> 
<DataTemplate x:Key="RedItemTemplate"> 
    <Viewbox MaxHeight="140" VerticalAlignment="Stretch"> 
     <TextBlock Text="{Binding Path=RedItem}" HorizontalAlignment="Center" Foreground="Red" /> 
    </Viewbox> 
</DataTemplate> 

<DataTemplate x:Key="GreenItemTemplate"> 
    <Viewbox MaxHeight="140" VerticalAlignment="Stretch"> 
     <TextBlock Text="{Binding Path=GreenItem}" HorizontalAlignment="Center" Foreground="Green" /> 
    </Viewbox> 
</DataTemplate> 

<DataTemplate x:Key="BlackItemTemplate"> 
    <Viewbox MaxHeight="140" VerticalAlignment="Stretch"> 
     <TextBlock Text="{Binding Path=BlackItem}" HorizontalAlignment="Center" Foreground="LightGray" /> 
    </Viewbox> 
</DataTemplate> 

<Style x:Key="ListViewStyle" TargetType="{x:Type ListViewItem}"> 
    <Setter Property="Background" Value="Transparent" /> 
    <Setter Property="HorizontalContentAlignment" Value="Stretch" /> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type ListViewItem}"> 
       <Border x:Name="Bd" Background="{TemplateBinding Background}" 
         SnapsToDevicePixels="True" BorderThickness="0,0,0,1" BorderBrush="Transparent"> 
        <GridViewRowPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}" /> 
       </Border> 
       <ControlTemplate.Triggers> 
        <Trigger Property="IsSelected" Value="false" /> 
        <Trigger Property="IsMouseOver" Value="false" /> 
       </ControlTemplate.Triggers> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

사용자 정의 속성

/// <summary> 
/// ListViewColumnStretch 
/// </summary> 
public class ListViewColumns : DependencyObject 
{ 

    #region Fields 

    /// <summary> 
    /// Holds a reference to our parent ListView control 
    /// </summary> 
    private ListView _parentListView = null; 

    #endregion 

    #region Dependency Property Infrastructure 

    /// <summary> 
    /// IsStretched Dependency property which can be attached to gridview columns. 
    /// </summary> 
    public static readonly DependencyProperty StretchProperty = 
     DependencyProperty.RegisterAttached("Stretch", 
     typeof(bool), 
     typeof(ListViewColumns), 
     new UIPropertyMetadata(true, null, OnCoerceStretch)); 


    /// <summary> 
    /// Gets the stretch. 
    /// </summary> 
    /// <param name="obj">The obj.</param> 
    /// <returns></returns> 
    public static bool GetStretch(DependencyObject obj) 
    { 
     return (bool)obj.GetValue(StretchProperty); 
    } 

    /// <summary> 
    /// Sets the stretch. 
    /// </summary> 
    /// <param name="obj">The obj.</param> 
    /// <param name="value">if set to <c>true</c> [value].</param> 
    public static void SetStretch(DependencyObject obj, bool value) 
    { 
     obj.SetValue(StretchProperty, value); 
    } 

    /// <summary> 
    /// Called when [coerce stretch]. 
    /// </summary> 
    /// <remarks>If this callback seems unfamilar then please read 
    /// the great blog post by Paul jackson found here. 
    /// http://compilewith.net/2007/08/wpf-dependency-properties.html</remarks> 
    /// <param name="source">The source.</param> 
    /// <param name="value">The value.</param> 
    /// <returns></returns> 
    public static object OnCoerceStretch(DependencyObject source, object value) 
    { 
     ListView lv = (source as ListView); 

     //Ensure we dont have an invalid dependency object of type ListView. 
     if (lv == null) 
      throw new ArgumentException("This property may only be used on ListViews"); 

     //Setup our event handlers for this list view. 
     lv.Loaded += new RoutedEventHandler(lv_Loaded); 
     lv.SizeChanged += new SizeChangedEventHandler(lv_SizeChanged); 
     return value; 
    } 

    #endregion 

    #region Event Handlers 

    /// <summary> 
    /// Handles the SizeChanged event of the lv control. 
    /// </summary> 
    /// <param name="sender">The source of the event.</param> 
    /// <param name="e">The <see cref="System.Windows.SizeChangedEventArgs"/> instance containing the event data.</param> 
    private static void lv_SizeChanged(object sender, SizeChangedEventArgs e) 
    { 
     ListView lv = (sender as ListView); 
     if (lv.IsLoaded) 
     { 
      //Set our initial widths. 
      SetColumnWidths(lv); 
     } 
    } 

    /// <summary> 
    /// Handles the Loaded event of the lv control. 
    /// </summary> 
    /// <param name="sender">The source of the event.</param> 
    /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param> 
    private static void lv_Loaded(object sender, RoutedEventArgs e) 
    { 
     ListView lv = (sender as ListView); 
     //Set our initial widths. 
     SetColumnWidths(lv); 
    } 
    #endregion 

    #region Private Members 

    /// <summary> 
    /// Sets the column widths. 
    /// </summary> 
    private static void SetColumnWidths(ListView listView) 
    { 
     //Pull the stretch columns fromt the tag property. 
     List<GridViewColumn> columns = (listView.Tag as List<GridViewColumn>); 
     double specifiedWidth = 0; 
     GridView gridView = listView.View as GridView; 
     if (gridView != null) 
     { 
      if (columns == null) 
      { 
       //Instance if its our first run. 
       columns = new List<GridViewColumn>(); 
       // Get all columns with no width having been set. 
       foreach (GridViewColumn column in gridView.Columns) 
       { 
        if (!(column.Width >= 0)) 
         columns.Add(column); 
        else specifiedWidth += column.ActualWidth; 
       } 
      } 
      else 
      { 
       // Get all columns with no width having been set. 
       foreach (GridViewColumn column in gridView.Columns) 
        if (!columns.Contains(column)) 
         specifiedWidth += column.ActualWidth; 
      } 

      // Allocate remaining space equally. 
      foreach (GridViewColumn column in columns) 
      { 
       double newWidth = (listView.ActualWidth - specifiedWidth)/columns.Count; 
       if (newWidth >= 0) column.Width = newWidth - 10; 
      } 

      //Store the columns in the TAG property for later use. 
      listView.Tag = columns; 
     } 
    } 


    #endregion 

} 
+1

어느 쪽이 잘리고 있습니까? 오른쪽 또는 아래? – coldandtired

+0

하단이 잘 리거나 줄기의 목적이 끊어지는 것을 방지하기위한 것입니다. –

답변

0

이것은 약간 간접적이지만 한 컨트롤의 한계에 직면했을 때 다른 방법을 시도해보십시오. ListView의 GridView를 사용하는 대신 DataGrid를 사용해보십시오. 비례 열 증가가 가능합니다. 난 그냥 당신 'XAML에서 버전을 박탈를 게시 할 예정입니다,하지만 당신은 포인트를 얻을 것이다 (폭이다 = "33 *")

<DataGrid> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Red" Width="33*"/> 
     <DataGridTextColumn Header="Green" Width="33*"/> 
     <DataGridTextColumn Header="Black" Width="33*"/> 
    </DataGrid.Columns> 
</DataGrid> 
2

내가 여기이 오래된 질문 알지만,은 다른 사람을위한 또 다른 해결책. ListViewItem 스타일에서 HorizontalAlignment를 Stretch로 설정하고 With를 Auto로 설정합니다.

<!--ListViewItem--> 
    <Style TargetType="ListViewItem" x:Key="ListViewItemStyle"> 
     <Setter Property="HorizontalContentAlignment" Value="Stretch" /> 
     <Setter Property="HorizontalAlignment" Value="Stretch" /> 
     <Setter Property="Width" Value="Auto" /> 
    </Style> 
관련 문제