【问题标题】:Toolbar button styles get ignored?工具栏按钮样式被忽略?
【发布时间】:2010-03-09 01:36:08
【问题描述】:

我在 WPF 的工具栏上有按钮。

当我执行 XAML 时:

<ToolBar.Resources>
   <Style TargetType="{x:Type Button}">
      <Setter Property="Width" Value="21"></Setter>
      <Setter Property="Height" Value="21"></Setter>
   </Style>
</ToolBar.Resources>

工具栏上的按钮都没有相应地设置它们的大小。

我必须转到每个按钮并手动将它们的宽度和高度设置为所需的值。

知道为什么工具栏上的样式不起作用吗?

【问题讨论】:

    标签: wpf styles toolbar


    【解决方案1】:

    这是因为ToolBar 将ToolBar.ButtonStyleKey 标识的样式应用于按钮,而不是让它们保留默认样式。 (这就是为什么工具栏中的按钮是扁平的,即使默认样式被提升了。)Reference。

    你需要“劫持”这个样式,而不是默认样式:

    <ToolBar.Resources>
      <Style x:Key="{x:Static ToolBar.ButtonStyleKey}" TargetType="Button">
        <Setter Property="Width" Value="100" />
      </Style>
    </ToolBar.Resources>
    

    注意样式声明中的 x:Key。

    【讨论】:

      【解决方案2】:

      如果要向工具栏添加硬编码按钮,可以将 ToolBar.ItemContainerStyle 设置为自定义样式以获得所需的效果。

      <ToolBar.ItemContainerStyle>
          <Style
              TargetType="Button">
              <Setter
                  Property="Width"
                  Value="21" />
              <Setter
                  Property="Height"
                  Value="21" />
          </Style>
      </ToolBar.ItemContainerStyle>
      

      如果您使用的是 ToolBar.ItemsSource,则可以改为使用 ToolBar.ItemTemplate 为工具栏数据定义模板。

      <ToolBar.ItemTemplate>
          <DataTemplate>
              <Button
                  Width="21"
                  Height="21"
                  Content="{Binding}" />
          </DataTemplate>
      </ToolBar.ItemTemplate>
      

      请注意,在某些情况下,可以同时使用这两种方法以提高灵活性。

      这不仅适用于工具栏,还适用于 ItemsControl 的所有派生类。

      祝你好运,

      【讨论】:

        【解决方案3】:

        如the other answer 中所述,工具栏会自动将自己的样式应用于添加到其中的许多/最典型的控件。

        作为劫持其样式键或手动将您自己的样式应用于控件的替代方法,您可以替代它的方法,该方法首先设置其内部样式。简单例子:

        public class LessIsMoreToolbar : ToolBar
        {
            protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
            {
                // Nada
            }
        }
        

        然后在 XAML 中使用 &lt;local:LessIsMoreToolbar&gt; 而不是 &lt;Toolbar&gt;。

        请注意,这里 PrepareContainerForItemOverride() 专门不调用 base.PrepareContainerForItemOverride()`。这就是消除样式设置的原因。您可以view the base's version of this method yourself 验证这不会消除您需要的任何东西。

        需要注意的是PrepareContainerForItemOverrideis defined by ItemsControl,它就像Toolbar 的曾祖父母。它的这个方法的版本启动了其他一些Prepare... 案例,你也应该小心不会破坏任何东西。您不能 (or perhaps shouldn't) 直接调用该版本的方法。

        但最后,如果它适合你,那么这是一个很好的简单方法。

        【讨论】:

          猜你喜欢
          • 2012-01-18
          • 1970-01-01
          • 1970-01-01
          • 2014-01-01
          • 2022-06-18
          • 1970-01-01
          • 2022-01-14
          • 1970-01-01
          • 2016-07-24
          相关资源
          最近更新 更多