首页 > 解决方案 > 如何根据里面的内容设置翻转视图高度

问题描述

我需要根据里面的内容设置翻转视图的高度。它应该是最大的元素。Flipview 包含两个文本块,其中的文本可以有不同的大小。我尝试了以下

Mainpage.xaml 摘录

 <Page.DataContext>
    <local:Msg/>
</Page.DataContext>


<Grid Background="LightBlue">
    <Grid.RowDefinitions>

        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>

    </Grid.RowDefinitions>

    <!--<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">-->
    <FlipView  x:Name="flipView1" Grid.Row="0"  ItemsSource="{Binding CustomSearchResults}" Padding="20"
          BorderBrush="Black" Background="#DEDEDE" BorderThickness="1"  VerticalAlignment="Stretch" >
        <FlipView.ItemTemplate>
            <DataTemplate>
                
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition  Height="Auto"/>
                    </Grid.RowDefinitions>
                    
                    <TextBlock   Grid.Row="0" Text="{Binding Text1}" FontFamily="Segoe UI"   TextWrapping="WrapWholeWords"
                           TextTrimming="CharacterEllipsis" Margin="0,0,0,20"       />

                    <TextBlock Grid.Row="1" Text="{Binding Text2}" FontFamily="Segoe UI" TextWrapping="WrapWholeWords"
                               TextTrimming="CharacterEllipsis"  
                                   />
                    
                </Grid>
            </DataTemplate>
        </FlipView.ItemTemplate>
    </FlipView>
    <!--</ScrollViewer>-->
</Grid>

数据上下文类摘录

     public class CustomSearchResult
    {
        public string Text1 { get; set; }
        public string Text2 { get; set; }
    }
    public class Msg
    {

        public Msg()
        {
            CustomSearchResults = new List<CustomSearchResult>();
            CustomSearchResults.Add(new CustomSearchResult
            {
                Text1 = "Hardware Trends in 2021 - Online Computer Tips....",
                Text2 = @"Famous chipmaker AMD developed a few new products. According to the latest rumors, along with the third-generation EPYC server processors, a brand new product Ryzen 5000,
                        desktop CPU based on Zen 3 architecture will be only the first of its kind, released in 2021."
            });
            CustomSearchResults.Add(new CustomSearchResult
            {
                Text1 = "What are the latest trends in hardware technology? – AnswersToAll",
                Text2 = @"What are the latest trends in hardware technology? Current trends in hardware and software include the increasing use of reduced instruction-set computing, migration to the UNIX operating system, the development of large software libraries, 
                           microprocessor-based smart terminals that allow remote validation of data, speech synthesis and recognition, application …&quot;
            });

            CustomSearchResults.Add(new CustomSearchResult
            {
                Text1 = "Kitchen cabinet hardware 2021-2022: latest trends and stylish …&quot;,
                Text2 = @"One of the 2022 kitchen trends is the geometric forms. We suggest you incorporate this idea into your kitchen cabinet hardware. It will offer the decor 
                        a point of interest and emphasize the sharp lines of the cabinets. Furthermore, this design will integrate perfectly in any style and enrich it with stability. Large Text
 Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text Large Text
 Large Text"
            });
        }

        public List<CustomSearchResult> CustomSearchResults { get; set; }


    }

Flipview 应用截图 在此处输入图像描述

翻转视图的高度应该缩小到最大的内容。我尝试将scrollviewer 包裹在flipview 周围,但没有成功。我应用了 arttribute verticalalignment=stretch 没有运气。我听说在自定义布局时使用了诸如 measureoverride() 之类的测量和排列阶段,但我不确定需要为此挂钩哪个事件

标签: xamluwpuwp-xaml

解决方案


您可以通过计算FlipViewItem加载事件中的所有高度然后更改FlipView高度来实现这一点。

首先,您必须稍微修改一下您的 Xaml。默认ItemsPanel是使用虚拟化FlipViewVirtualizingStackPanel。这意味着FlipView将只创建几个itemcontainers并重用这些容器。这将阻止我们找到所有项目并获得高度。所以我们只需要将 更改ItemsPanelStackPanel.

然后您需要将填充添加到Gird项目模板内部,而不是将填充添加到FlipView.

最后,您需要在后面添加一个名称,TextBlock以便稍后在后面的代码中找到它们。

这是修改后的代码:

<!--<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">-->
<FlipView x:Name="flipView1" Grid.Row="0"  ItemsSource="{Binding CustomSearchResults}"
  BorderBrush="Black" Background="#DEDEDE" BorderThickness="1"  VerticalAlignment="Stretch" >
    <FlipView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel AreScrollSnapPointsRegular="False" Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </FlipView.ItemsPanel>
    <FlipView.ItemTemplate>
        <DataTemplate>

            <Grid Padding="20" >
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition  Height="Auto"/>
                </Grid.RowDefinitions>

                <TextBlock x:Name="FirstTextBlock"  Grid.Row="0" Text="{Binding Text1}"  FontFamily="Segoe UI"   TextWrapping="WrapWholeWords"
                   TextTrimming="CharacterEllipsis" Margin="0,0,0,20"       />

                <TextBlock x:Name="SecondTextBlock" Grid.Row="1" Text="{Binding Text2}" FontFamily="Segoe UI" TextWrapping="WrapWholeWords"
                       TextTrimming="CharacterEllipsis"  
                           />

            </Grid>
        </DataTemplate>
    </FlipView.ItemTemplate>
</FlipView>
<!--</ScrollViewer>-->

在后面的代码中你首先需要做的是找到里面的所有项目FlipView,然后计算两者的总高度TextBlock。然后找到所有项目的最大高度。

这是代码:

public double TextMaxHeight { get; set; }

public MainPage()
{
    this.InitializeComponent();
    TextMaxHeight = 0;
    this.Loaded += MainPage_Loaded;
}

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    // get every item and Calculate it's height
    for (int i = 0; i < flipView1.Items.Count; i++)
    {
        var item = flipView1.Items[i];
        // get item container
        var _Container = flipView1.ContainerFromItem(item);
        // find the first textblock
        var _FirstBlock = (TextBlock)FindMyChildByName(_Container, "FirstTextBlock");
        var size = _FirstBlock.ActualHeight;
        // find the second textblock
        var _SecondBlock = (TextBlock)FindMyChildByName(_Container, "SecondTextBlock");
        var size2 = _SecondBlock.ActualHeight;

        //check the max height over all the items
        TextMaxHeight = TextMaxHeight > size + size2 ? TextMaxHeight : size + size2;

    }
    // change flipview's height.  40 for padding and 20 for the first textblock margin
    flipView1.Height = TextMaxHeight + 60;
}

public static DependencyObject FindMyChildByName(DependencyObject parant, string ControlName)
{
    int count = VisualTreeHelper.GetChildrenCount(parant);

    for (int i = 0; i < count; i++)
    {
        var MyChild = VisualTreeHelper.GetChild(parant, i);
        if (MyChild is FrameworkElement && ((FrameworkElement)MyChild).Name == ControlName)
            return MyChild;

        var FindResult = FindMyChildByName(MyChild, ControlName);
        if (FindResult != null)
            return FindResult;
    }

    return null;
}

推荐阅读