【问题标题】:Why aren't my WPF radio buttons vertically aligned to the center?为什么我的 WPF 单选按钮不垂直对齐到中心?
【发布时间】:2014-09-20 10:32:45
【问题描述】:

我有一个 WPF 项目,我正在尝试使用单选按钮来确定要使用哪个 TextBox 输入。但是,当我运行它时,单选按钮本身与容器的顶部对齐,我找不到任何影响它的对齐属性。这种行为是预期的吗?我一直在寻找答案,但似乎一切都在问如何垂直对齐单选按钮。我的假设是它与我将它嵌套在其他控件中的方式有​​关,但是我怎样才能让它在不做太多改变的情况下工作呢?

这是与单选按钮相关的 xaml:

<DockPanel Grid.Column="1" Margin="5,0,0,0">
  <RadioButton HorizontalContentAlignment="Stretch" DockPanel.Dock="Top" IsChecked="True">
    <xctk:TimePicker Name="TimePickerBox" Margin="0" Format="LongTime"
                     VerticalAlignment="Center"/>
  </RadioButton>
  <RadioButton Margin="0,5,0,0" DockPanel.Dock="Top">
    <StackPanel Orientation="Horizontal">
      <TextBox Name="Hours" Width="30" VerticalAlignment="Center">0</TextBox>
      <Label>Hours</Label>
      <TextBox Name="Minutes" Width="30" VerticalAlignment="Center">0</TextBox>
      <Label>Minutes</Label>
      <TextBox Name="Seconds" Width="30" VerticalAlignment="Center">0</TextBox>
      <Label>Seconds</Label>
    </StackPanel>
  </RadioButton>
// ...

这就是它的样子:

如何让单选按钮垂直居中?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    我真的不记得DockPanel.Dock 做了什么,但尝试将StackPanelVerticalAligment 设置为Center,如果没有帮助,也将DockPanel.Dock 设置为Center

    <RadioButton Margin="0,5,0,0" DockPanel.Dock="Center">
      <StackPanel VerticalAlignment="Center" Orientation="Horizontal">
        <TextBox Name="Hours" Width="30" VerticalAlignment="Center">0</TextBox>
        <Label>Hours</Label>
        <TextBox Name="Minutes" Width="30" VerticalAlignment="Center">0</TextBox>
        <Label>Minutes</Label>
        <TextBox Name="Seconds" Width="30" VerticalAlignment="Center">0</TextBox>
        <Label>Seconds</Label>
      </StackPanel>
    </RadioButton>
    

    【讨论】:

      【解决方案2】:

      为 RadioButton 设置 VerticalContentAlignmentCenter

      <RadioButton Margin="0,5,0,0" DockPanel.Dock="Top"
                   VerticalContentAlignment="Center">
        .....
      </RadioButton>
      

      【讨论】:

      • VerticalAlignment 不足的原因有没有?与列表框之类的东西不同,单选按钮中没有“内容”。这只是 WPF 的怪事吗?
      • VerticalAlignment 将相对于其包含的父控件对齐控件,而 VerticalContentAlignment 将相对于其自身对齐内容。你是对的,单选按钮没有内容。如果您查看 radioButton 的默认模板,您会注意到 Border 的 VerticalAlignment 映射到 VerticalContentAlignment。 VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
      【解决方案3】:

      在两个RadioButton 元素上,尝试添加VerticalAlignment="Top" VerticalContentAlignment="Center"。我在一个测试项目中做到了这一点,它似乎可以解决问题。

      【讨论】:

        【解决方案4】:

        我复制了您的 XAML,它完全符合您的要求。所以这似乎还有另一个原因。
        请注意,radioButtons Bullet 将始终与其中的文本块的第一行对齐。
        如需进一步阅读,请参见此处: How do I make a RadioButton's Bullet align top? 解释一下。

        【讨论】:

          猜你喜欢
          • 2020-07-23
          • 2019-03-09
          • 1970-01-01
          • 2019-01-28
          • 2018-01-16
          • 1970-01-01
          • 2015-05-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多