【问题标题】:How to bind Height to parent's height minus another item's height如何将高度绑定到父母的高度减去另一个项目的高度
【发布时间】:2018-03-02 12:28:00
【问题描述】:

我有一个列表框,上面显示一个图像和一个文本。我已将 DataTemplate 绑定到具有字符串 Str 和图像 Image 的自定义 MyImage 类。由于周围的 StackPanel 是水平的,因此下一个图像将出现在第一个图像的右侧。

我无法将图像的高度设置为填充整个列表框高度减去文本高度和边距的值。 在下面的代码中,我将它绑定到 ListBox listboxMyImages 的 ActualHeight。 我希望现在能够从该值中减去 TextBlock 的高度。最好的方法是什么?

<ListBox x:Name="listboxMyImages"  Margin="10,10,10,10">
                                        <ListBox.ItemsPanel>
                                            <ItemsPanelTemplate>
                                                <StackPanel Orientation="Horizontal"/>
                                            </ItemsPanelTemplate>
                                        </ListBox.ItemsPanel>
                                        <ListBox.ItemTemplate>
                                            <DataTemplate DataType="{x:Type local:MyImage}">
                                                <StackPanel>
                                                    <TextBlock x:Name="lblMyImage" Margin="3" Text="{Binding Str}" />
                                                    <Image Margin="3" Source="{Binding Image}"  Height="{Binding ElementName=listboxMyImages, Path=ActualHeight }"/>
                                                </StackPanel>
                                            </DataTemplate>
                                        </ListBox.ItemTemplate>
                                    </ListBox>

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    使用另一个面板 - Grid 2 行

    <Grid>
    
    <Grid.RowDefinitions>
       <RowDefinition Height="Auto"/>
       <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    
    <TextBlock x:Name="lblMyImage" Margin="3" Text="{Binding Str}" />
    <Image Grid.Row="1" Margin="3" Source="{Binding Image}"/>
    
    </Grid>
    

    图像将拉伸并占用所有可用高度

    【讨论】:

    • 这实际上将图像拉伸到其原始大小并让我在 ListBox 中向下滚动。
    • itemspanel StackPanel 似乎允许项目的高度不受限制。我需要考虑改进
    • 好的,谢谢!当你想到什么时告诉我。
    【解决方案2】:

    您可以尝试使用这样的 Grid,而不是使用 StackPanel:

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*">
            <RowDefinition Height="Auto">
        </Grid.RowDefinitions>
    </Grid>
    

    不确定它是否有效,因为我现在无法尝试。

    【讨论】:

      猜你喜欢
      • 2011-01-15
      • 2012-10-16
      • 2018-11-28
      • 2016-03-21
      • 2017-04-29
      • 2016-10-22
      • 2018-08-09
      • 2010-12-16
      • 1970-01-01
      相关资源
      最近更新 更多