WPF如何有一个右对齐的列和文本换行的网格?

aemubtdh  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(131)

我需要有3列来显示以下数据:

  • 消息类型
  • 信息
  • 时间戳

有关时间戳的信息必须右对齐。

    • 理想条件:**
    • 我的XAML:**
<StackPanel Grid.Row="1" Margin="0,10,0,0">
    <ListView ItemsSource="{Binding MessagesCollectionView}">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>

                    <!--Grid's Left Column: containinng Messsage-->
                    <StackPanel Grid.Column="0" Orientation="Horizontal" Margin="0,0,0,10">
                        <TextBlock  Margin="10,0,0,0" Text="{Binding MessageLevelValue}" />
                        <TextBlock  Margin="10,0,0,0" Text="{Binding Message}" />
                    </StackPanel>

                    <!--Grid's Right Column: for TimeStamps-->
                    <StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right">
                        <TextBlock Grid.Column="1" Margin="10,0,0,0" HorizontalAlignment="Right" Text="{Binding TimeStamp}" />
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackPanel>
    • 问题:**如果消息较短,上述代码可以正常工作。如果消息较长,则不会显示TimeStamp列(如下面的屏幕截图所示):

5uzkadbs

5uzkadbs1#

如果需要三列,则应创建三个ColumnDefinitions
您可能还想禁用ListView的水平滚动条并将长文本换行。

<ListView ItemsSource="{Binding MessagesCollectionView}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>

                <!--Grid's Left Column: containinng Messsage-->
                <TextBlock  Margin="10,0,0,0" Text="{Binding MessageLevelValue}" />
                <TextBlock Grid.Column="1"  Margin="10,0,10,0" Text="{Binding Message}" TextWrapping="Wrap" />

                <!--Grid's Right Column: for TimeStamps-->
                <TextBlock Grid.Column="2" Margin="10,0,0,0" HorizontalAlignment="Right" Text="{Binding TimeStamp}" />
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

如果您仍然不能使它工作,那么请提供您的完整的XAML元素树从窗口下来,也请澄清您的要求。

相关问题