Выравнивание элементов ListBox - PullRequest
1 голос
/ 29 апреля 2020

Я пытаюсь установить выравнивание содержимого в ListBox ниже. Я обернул ListBox внутри ScrollViewer, чтобы он прокручивался по горизонтали.

Каждый элемент списка - это панель стека, и я пытаюсь выровнять каждый из них по верху и установить ширину для каждого из них автоматически.

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

Я поставил HorizontalContentAlignment="Left" и VerticalContentAlignment="Top", как я читал в подобных постах, но это ничего не меняет.

<ScrollViewer Grid.Row="1"   VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"  >
                <ListBox ItemsSource="{Binding Termene}" SelectedItem="{Binding SelectedTermenCondica}"  HorizontalContentAlignment="Left" VerticalContentAlignment="Top">
                    <ListBox.ItemsPanel>
                        <ItemsPanelTemplate>
                            <UniformGrid Rows="1"   />
                        </ItemsPanelTemplate>
                    </ListBox.ItemsPanel>
                    <ListBox.ItemTemplate >
                        <DataTemplate >
                            <StackPanel Margin="2"  >
                                <StackPanel.Resources>
                                    <CollectionViewSource Source="{Binding Dosare}" x:Key="dosareView"  IsLiveSortingRequested="True" >
                                        <CollectionViewSource.SortDescriptions>
                                            <scm:SortDescription PropertyName="Ora" />
                                        </CollectionViewSource.SortDescriptions>
                                    </CollectionViewSource>
                                    <Style x:Key="NoFocusColumStyle" TargetType="{x:Type DataGridCell}">
                                        <Setter Property="IsHitTestVisible" Value="False"/>
                                    </Style>
                                </StackPanel.Resources>
                                <TextBlock Text="{Binding NumeComplet, StringFormat='Complet {0}'}" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Top"></TextBlock>
                                <TextBlock Text="{Binding TermenCB, StringFormat='Termen: {0}'}" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Top"></TextBlock>
                                <DataGrid IsSynchronizedWithCurrentItem="True" CellStyle="{StaticResource NoFocusColumStyle}" IsReadOnly="True" ItemsSource="{Binding Source={StaticResource dosareView}}" Style="{StaticResource DGRapaorte}" AutoGenerateColumns="False" >

                                    <DataGrid.Columns>
                                        <DataGridTextColumn  Header="Nr. dosar" Binding="{Binding NumarDosar}"/>
                                        <DataGridTextColumn CanUserSort="True" SortDirection="Ascending" SortMemberPath="Ora"  Header="Ora" Binding="{Binding Ora, StringFormat={}{0:HH:mm}}" />
                                        <DataGridTextColumn Header="Obiect" Binding="{Binding Obiect}"/>
                                    </DataGrid.Columns>
                                </DataGrid>
                               </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </ScrollViewer>

Позже редактирование: я добавил некоторые данные (три элемента в Termene, чтобы показать вам, как это выглядит. Я их размыл , но вы можете увидеть проблему. Вот как это выглядит прямо сейчас: enter image description here

Прокручиваем дальше: enter image description here

Сейчас Вот как я бы хотел, чтобы это выглядело следующим образом: enter image description here

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

1 Ответ

1 голос
/ 02 мая 2020

Заменить часть сетки Uniform следующим:

<ItemsPanelTemplate>
    <StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>

Источник: { ссылка }

enter image description here

Этот пример работал для меня:

<Window x:Class="WpfMVVM.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfMVVM"
        mc:Ignorable="d"
        Title="MainWindow" Height="500" Width="500">
    <ListBox ItemsSource="{Binding Items}" VerticalContentAlignment="Top">
        <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="2">
                    <TextBlock Text="test" HorizontalAlignment="Center" FontWeight="Bold" />
                    <TextBlock Text="blub" HorizontalAlignment="Center" FontWeight="Bold" />
                    <DataGrid IsSynchronizedWithCurrentItem="True" IsReadOnly="True"
                              ItemsSource="{Binding DataGridItems}" AutoGenerateColumns="False">
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="Nr. dosar" Binding="{Binding Text}" />
                        </DataGrid.Columns>
                    </DataGrid>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>

с этой моделью представления

public class DataViewModel
{
    public DataViewModel()
    {

    }

    public List<Item> Items { get; set; } = new List<Item>()
    {
        new Item(){DataGridItems = new List<DataGridItem>(){new DataGridItem() { Text = "a"} }},
        new Item(){DataGridItems = new List<DataGridItem>(){new DataGridItem() { Text = "aaaaaaaaaaa"} }},
        new Item(){DataGridItems = new List<DataGridItem>(){new DataGridItem() { Text = "aaaaaaaaaaaaaaaaaa"} }},
        new Item(){DataGridItems = new List<DataGridItem>()
        {
            new DataGridItem() { Text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
            new DataGridItem() { Text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
            new DataGridItem() { Text = "aaa"},
            new DataGridItem() { Text = "aaaaaaaaaa"}
        }}
    };
}

public class Item
{
    public List<DataGridItem> DataGridItems { get; set; }
}

public class DataGridItem
{
    public string Text { get; set; }
}
...