2016-01-16 5 views
0

Я пытаюсь разработать универсальное приложение для личного использования, но я бегу в проблему, что второй столбец в моей ListView не выравнивать должным образом, у меня есть следующий XAML:XAML ListView авто ширина колонки

<ListView 
     Grid.Row="1" 

     ItemsSource="{Binding Items, UpdateSourceTrigger=PropertyChanged}"> 
     <ListView.ItemTemplate> 
      <DataTemplate> 
       <Grid> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="*" /> 
         <ColumnDefinition Width="Auto" /> 
        </Grid.ColumnDefinitions> 
        <Grid.RowDefinitions> 
         <RowDefinition Height="*" /> 
         <RowDefinition Height="1*" /> 
         <RowDefinition Height="1*" /> 
        </Grid.RowDefinitions> 
        <Image Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Stretch="None" Source="{Binding Image}" /> 
        <TextBlock Grid.Column="0" Grid.Row="2" Text="{Binding Name}" HorizontalAlignment="Center" /> 
        <Image Grid.Column="1" Grid.Row="1" Grid.RowSpan="2" Source="{StaticResource HighAlchImage}" /> 
       </Grid> 
      </DataTemplate> 
     </ListView.ItemTemplate> 
    </ListView> 

что приводит к следующему изображению:
enter image description here

Однако я хочу второе изображение (тот, который то же самое каждый раз), чтобы выровнять с собой, предпочтительно с шириной первого столбца для Авто , Это возможно?

ответ

0

Сделай наоборот:

<Grid.ColumnDefinitions> 
    <ColumnDefinition Width="Auto" /> 
    <ColumnDefinition Width="*" /> 
</Grid.ColumnDefinitions> 

Таким образом, ваш первый столбец будет использовать пространство, которое он нуждается, а второй столбец будет выравниваться.

+0

К сожалению, это, кажется, создает практически тот же результат. Кроме того, текст всегда полностью отображается, независимо от размера. – ManIkWeet

2

Grid панель такая функциональность встроена. Для того, чтобы использовать его, вы должны установить SharedSizeGroup на определениях столбцов, а затем установить прикрепленный Grid.IsSharedSizeScope на элемент родительских все сетки, которые должны разделить размеры столбцов (ListView будет хорошим выбором в твоем случае).

<ListView Grid.Row="1" 
      ItemsSource="{Binding Items, UpdateSourceTrigger=PropertyChanged}" 
      Grid.IsSharedSizeScope="True"> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
      <Grid> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="Auto" SharedSizeGroup="Column1" /> 
        <ColumnDefinition Width="Auto" SharedSizeGroup="Column2" /> 
       </Grid.ColumnDefinitions> 
       <Grid.RowDefinitions> 
        <RowDefinition Height="*" /> 
        <RowDefinition Height="1*" /> 
        <RowDefinition Height="1*" /> 
       </Grid.RowDefinitions> 
       <Image Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Stretch="None" Source="{Binding Image}" /> 
       <TextBlock Grid.Column="0" Grid.Row="2" Text="{Binding Name}" HorizontalAlignment="Center" /> 
       <Image Grid.Column="1" Grid.Row="1" Grid.RowSpan="2" Source="{StaticResource HighAlchImage}" /> 
      </Grid> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 

Вы можете принять некоторые меры предосторожности при выборе значения SharedSizeGroup свойств - предпочтительно, они должны быть уникальными для каждого визуального дерева.

+0

Есть ли эквивалент для приложений для хранилищ Windows? (Упомянул универсальное приложение в оригинальной записи) – ManIkWeet

0

Вам нужно растянуть ширину ListViewItem до ширины ListView.

i.e. Вы должны установить HorizontalContentAlignment из списка ListView в Stretch.

Обычно я хотел бы создать копию по умолчанию ListViewItemStyle, то не моя настройка на основе стиля по умолчанию:

(поместите следующий код внутри <ListView> Tag)

<ListView.Resources> 
    <!-- Better to put this to another XAML file --> 
    <Style x:Key="ListViewItemStyleDefault" TargetType="ListViewItem"> 
     <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/> 
     <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/> 
     <Setter Property="Background" Value="Transparent"/> 
     <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/> 
     <Setter Property="TabNavigation" Value="Local"/> 
     <Setter Property="IsHoldingEnabled" Value="True"/> 
     <Setter Property="Padding" Value="12,0,12,0"/> 
     <Setter Property="HorizontalContentAlignment" Value="Left"/> 
     <Setter Property="VerticalContentAlignment" Value="Center"/> 
     <Setter Property="MinWidth" Value="{ThemeResource ListViewItemMinWidth}"/> 
     <Setter Property="MinHeight" Value="{ThemeResource ListViewItemMinHeight}"/> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="ListViewItem"> 
        <ListViewItemPresenter CheckBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}" ContentMargin="{TemplateBinding Padding}" CheckMode="Inline" ContentTransitions="{TemplateBinding ContentTransitions}" CheckBoxBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}" DragForeground="{ThemeResource ListViewItemDragForegroundThemeBrush}" DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}" DragBackground="{ThemeResource ListViewItemDragBackgroundThemeBrush}" DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}" FocusBorderBrush="{ThemeResource SystemControlForegroundAltHighBrush}" FocusSecondaryBorderBrush="{ThemeResource SystemControlForegroundBaseHighBrush}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" PointerOverForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}" PressedBackground="{ThemeResource SystemControlHighlightListMediumBrush}" PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" PointerOverBackground="{ThemeResource SystemControlHighlightListLowBrush}" ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}" SelectedPressedBackground="{ThemeResource SystemControlHighlightListAccentHighBrush}" SelectionCheckMarkVisualEnabled="True" SelectedForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}" SelectedPointerOverBackground="{ThemeResource SystemControlHighlightListAccentMediumBrush}" SelectedBackground="{ThemeResource SystemControlHighlightListAccentLowBrush}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
    <Style x:Key="ListViewItemStyleStretch" TargetType="ListViewItem" BasedOn="{StaticResource ListViewItemStyleDefault}"> 
     <!-- Magic here --> 
     <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
    </Style> 
</ListView.Resources> 
<ListView.ItemContainerStyle> 
    <StaticResource ResourceKey="ListViewItemStyleStretch"/> 
</ListView.ItemContainerStyle> 
<ListView.ItemTemplate> 
    <!-- Your ItemTemplate... --> 
</ListView.ItemTemplate> 
0

В поисках решения, Я оказался здесь, @Ryan ответ близок к решению моей проблемы, но некоторые настройки должны быть выполнены.

1 Создать стиль:

<Style x:Key="LstViewItemContainerStyle" TargetType="ListViewItem"> 
    <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
</Style> 

2 Применить стиль к просмотру списка, как это:

<ListView 
    ... 
    ItemContainerStyle="{StaticResource LstViewItemContainerStyle}"> 
</ListView> 
Смежные вопросы