如何根据里面的内容设置flipview高度

How to set flipview height based on content inside

我需要根据内容设置 flipview 高度 inside.It 应该是最大的元素。 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>

数据上下文class摘录

     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 …"
            });

            CustomSearchResults.Add(new CustomSearchResult
            {
                Text1 = "Kitchen cabinet hardware 2021-2022: latest trends and stylish …",
                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() 之类的measure 和arrange 阶段用于自定义布局,但我不确定需要挂接哪个事件

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

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

那么您需要将填充添加到项目模板内的 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;
}