首页 > 解决方案 > 为什么将子元素绑定到父级 ActualWidth 属性使其太大?

问题描述

我有一个ListBox包含 DataTemplate,我想在其中使用 Dockpanel 让最后一个孩子填满可用空间(在我的例子中,最后一个孩子是文本块,它将在中心呈现)。

为此,我有以下代码(删除了 ComboBox 上的其他 DataTemplate,因为在我的问题的上下文中不需要它):

<ListBox x:Name="IsoLimitsList" ItemsSource="{Binding ISOLimits}" SelectedValue="{Binding SelectedISOLimit}" Margin="10, 0" BorderThickness="0" 
            Padding="0"  HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <DockPanel LastChildFill="True" Width="{Binding Path=ActualWidth, ElementName=IsoLimitsList}">
                <CheckBox IsChecked="{Binding IsActive}" DockPanel.Dock="Left" VerticalAlignment="Center"/>    
                <ComboBox ItemsSource="{Binding Path=DataContext.AllOxyColors, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" 
                            Width="150" DockPanel.Dock="Right" SelectedValue="{Binding Color, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Value" VerticalAlignment="Center" HorizontalAlignment="Stretch"/>
                <TextBlock Text="{Binding Name}" Margin="5, 2" VerticalAlignment="Center" HorizontalAlignment="Stretch" />
            </DockPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这工作得很好,除了 Dockpanel 只是太大了几个像素,导致列表框中的滚动条:

在此处输入图像描述

问题是:额外的宽度从何而来?我可以删除额外的宽度而不必编写另一个数据转换器吗?

到目前为止我已经尝试过:

标签: wpfxamldata-binding

解决方案


推荐阅读