wpf - WPF 复选框内容相对于复选框的垂直对齐

标签 wpf checkbox wpf-controls

我有一个复选框,其 XAML 标记如下:

<CheckBox HorizontalContentAlignment="Stretch">
    <StackPanel Orientation="Vertical">
        <TextBox x:Name="editTextBox" 
            Text="{Binding Path=Caption, Mode=TwoWay}"
            TextWrapping="Wrap"
            Visibility="{Binding Path=IsBeingEdited, Converter={StaticResource booleanToVisibilityConverter}}" />
        <TextBlock x:Name="itemText"
            TextWrapping="Wrap"                        
            Text="{Binding Path=Caption}" 
            Visibility="{Binding Path=IsBeingEdited, Converter={StaticResource reverseBooleanToVisibilityConverter}}">
        </TextBlock>
    </StackPanel>
</CheckBox>

这个想法是我可以在 TextBlock(显示)和 TextBox(编辑)之间切换。但是,运行应用程序时,CheckBox 视觉对象(可检查的正方形)垂直居中。我希望它与 TextBlock/TextBox 的顶部对齐。

我注意到,当我只包含一个 TextBlock(因此没有 StackPanel,没有 TextBox)时,该复选框实际上与 TextBlock 的顶部对齐,所以我假设我缺少 StackPanel 上的一些设置?

最佳答案

首先,不要在 VerticalAlignment 上浪费时间。或VerticalContentAlignment (甚至 ControlTemplate )。他们不会做你想要或可能期望的事情。

MSDN 中所述一个BulletDecorator (这是 CheckBox 和 RadioButton 用于呈现单选/复选按钮的控件)将自动设置图标的位置。您对此没有额外的控制权:

A Bullet always aligns with the first line of text when the Child object is a text object. If the Child object is not a text object, the Bullet aligns to the center of the Child object.

除非您更改控件模板(不必要),否则您只能在内容是文本的情况下将单选/复选图标放置在顶部。

所以,如果你这样做,它看起来不会很好,因为无论有多少 VerticalAlignment 你都无法移动图标。您尝试设置的属性。

<RadioButton>
    <StackPanel>
        <TextBlock Text="First line"/>
        <TextBlock Text="Something else"/>
    </StackPanel>
</RadioButton>

但是幸运的是,您可以在 TextBlock 中放入几乎任何您想要的东西。使用InlineUIContainer 。第一行中的文本(或内容)将自动指示图标的位置。如果您想要第一行下方的非文本内容,只需使用 <Linebreak/>然后<InlineUIContainer/>

这是一个具有超大 TextBox 的示例更清楚地显示正在发生的事情。

<RadioButton>

    <TextBlock VerticalAlignment="Top" TextWrapping="Wrap">

        <TextBlock Text="Products with &lt;" VerticalAlignment="Center" Margin="0,0,5,0"/>

        <InlineUIContainer BaselineAlignment="Center">
            <TextBox FontSize="30" Width="25" Text="10" Margin="0,0,5,0"/>          
        </InlineUIContainer>

        <TextBlock VerticalAlignment="Center" Margin="0,0,5,0">
            <Run Text="days" FontWeight="Bold"/>
            <Run Text="inventory" />
        </TextBlock>

        <LineBreak/>    

        <InlineUIContainer>
            <StackPanel>
                <CheckBox Content="Include unsold products" />
                <CheckBox Content="Include something else" />
            </StackPanel>
        </InlineUIContainer>

    </TextBlock>
</RadioButton>

关于wpf - WPF 复选框内容相对于复选框的垂直对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3863363/

相关文章:

c# - wpf collectionview 多过滤器

c# - ICommand.CanExecute 异步

checkbox - 在谷歌表单中创建带有文本框的复选框

wpf - 在WPF中动态添加网格和控件

wpf - Items控制项,走出视野

c# - 如何设置依赖属性值?

列表框中的 WPF UserControl,将 ICommand 绑定(bind)到 ViewModel

checkbox - Google 表格 - 当复选框放置在大范围内的特定单元格中时,只允许选中一个复选框

excel - 从 Checkbox 宏中排除行或列

WPF - 如何制作自定义边框