问题 如何使按钮的宽度自动调整按钮的文本?


我目前正在这样做,但我做错了:):

   <Style TargetType="{x:Type Button}">
      <Setter Property="MinWidth" Value="90" />
      <Setter Property="Width" Value="Auto" />
   </Style>

我希望按钮具有一些最小宽度,但也要使其宽度扩展以适合按钮的文本。


8775
2017-09-11 07:16


起源



答案:


您需要做的是将Horizo​​ntalAlignment属性设置为Center(或Right或Left)。按钮必须由包含的面板拉伸。

   <Style TargetType="{x:Type Button}">
      <Setter Property="MinWidth" Value="90" />
      <Setter Property="HorizontalAlignment" Value="Center" />
   </Style>

14
2017-09-11 07:49





如果设置 HorizontalAlignment 不工作,检查你没有设置 Width  - 这将阻止按钮调整大小。一个方便的技巧是设置 Width 财产 NaN 要么 ..NaN 取决于您的应用程序的配置(这不会引发编译错误)。


2
2017-11-06 18:30





如果您只设置MinWidth of button,如果您的文字宽度大于min width,它将自动展开,但相反情况下按钮将与您的最小宽度相同,

<Style TargetType="{x:Type Button}">
      <Setter Property="MinWidth" Value="90" />
</Style>

这足以存档到所需的结果


0
2017-09-11 07:28



嗯,为什么它不起作用呢......包含元素的风格是否会弄乱按钮?他们仍然伸展着...... - Alex Baranosky
啊......我不得不补充:<Setter Property =“Horizo​​ntalAlignment”Value =“Center”/>我相信堆栈面板将它们设置为拉伸。 - Alex Baranosky


答案:


您需要做的是将Horizo​​ntalAlignment属性设置为Center(或Right或Left)。按钮必须由包含的面板拉伸。

   <Style TargetType="{x:Type Button}">
      <Setter Property="MinWidth" Value="90" />
      <Setter Property="HorizontalAlignment" Value="Center" />
   </Style>

14
2017-09-11 07:49





如果设置 HorizontalAlignment 不工作,检查你没有设置 Width  - 这将阻止按钮调整大小。一个方便的技巧是设置 Width 财产 NaN 要么 ..NaN 取决于您的应用程序的配置(这不会引发编译错误)。


2
2017-11-06 18:30





如果您只设置MinWidth of button,如果您的文字宽度大于min width,它将自动展开,但相反情况下按钮将与您的最小宽度相同,

<Style TargetType="{x:Type Button}">
      <Setter Property="MinWidth" Value="90" />
</Style>

这足以存档到所需的结果


0
2017-09-11 07:28



嗯,为什么它不起作用呢......包含元素的风格是否会弄乱按钮?他们仍然伸展着...... - Alex Baranosky
啊......我不得不补充:<Setter Property =“Horizo​​ntalAlignment”Value =“Center”/>我相信堆栈面板将它们设置为拉伸。 - Alex Baranosky