34

在一个窗口中,我有一个DockPanels 列表来指定几个文件。每个 DockPanel 都有一个 TextBox(用于路径)和一个按钮(用于浏览文件)。

我重新创建了一个简单的 WPF 页面来演示这里的问题:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="150"
    Height="22">
    <DockPanel>
        <TextBox HorizontalAlignment="Stretch"/> <!-- path to file -->
        <Button Content="..." DockPanel.Dock="Right"/> <!-- button to browse for file -->
    </DockPanel>
</Page>

问题是我想要文本框右侧的按钮,但这会导致文本框非常小,因为 DockPanel 的 LastChild 是它用完剩余空间的按钮。我试图通过改变它们并设置来改变这一点,LastChildFill="False"但这只会导致按钮再次变小,而不会使 TextBox 变宽(即使使用HorizontalAlignment="Stretch")。

我希望按该顺序控制控件的原因是我希望用户在使用tab在窗口中导航时到达按钮之前的文本框。我研究了设置TabIndex,但感觉很hacky,WPF最喜欢的功能是tabindex按照XAML中定义的控制顺序排列。更不用说我可能必须在窗口中的所有内容上手动设置 TabIndex。

对我来说, TextBox.Horizo​​ntalAlignment 的设置似乎没有得到尊重。如何使第一个控件使用尽可能多的空间但仍保留制表符顺序?

4

2 回答 2

52

让它像这样:

<DockPanel LastChildFill="True">
    <Button Content="..." DockPanel.Dock="Right"/> <!-- button to browse for file -->
    <TextBox DockPanel.Dock="Left" HorizontalAlignment="Stretch"/> <!-- path to file -->
</DockPanel>
于 2010-11-05T04:15:52.310 回答
31

如果您不想要 DockPanel 的行为,请不要使用 DockPanel。

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <TextBox />
    <Button Content="..." Grid.Column="1"/>
</Grid>
于 2010-09-09T16:31:21.493 回答