【问题标题】:Is it possible to style a BulletDecorator in WPF?是否可以在 WPF 中设置 BulletDecorator 的样式?
【发布时间】:2010-12-13 15:56:11
【问题描述】:

显然它可以应用一个样式 - 试图找出是否可以在样式中定义 Bullet 元素,因此您不必在 XAML 中一遍又一遍地定义它

<BulletDecorator>
       <BulletDecorator.Bullet>
            ...my bullet UIElement here...
        </BulletDecorator.Bullet>
        <TextBlock>
            ... my text here...
        </TextBlock>
</BulletDecorator> 

【问题讨论】:

    标签: wpf styles


    【解决方案1】:

    BulletDecorator.Bullet 无法设置样式,并且 BulletDecorator 不是控件,因此无法进行模板化。

    但是,您可以通过为 ContentControl 定义一个 ControlTemplate 来获得纯 XAML 中的效果,如下所示:

    <ControlTemplate x:Key="BulletTemplate" TargetType="{x:Type ContentControl}">
      <BulletDecorator>
        <BulletDecorator.Bullet>
          ...my bullet UIElement here...
        </BulletDecorator.Bullet>
        <ContentPresenter />
      </BulletDecorator>
    </ControlTemplate>
    

    现在你可以像这样使用它了:

    <ContentControl Template="{StaticResource BulletTemplate}">
      <TextBlock />
    </ContentControl>
    

    如果您只使用它几次,“

    public class MyBullet : ContentControl
    {
      static MyBullet()
      {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyBullet), new FrameworkPropertyMetadata(typeof(MyBullet));
      }
    }
    

    然后将您的 ControlTemplate 移动到 Theme/Generic.xaml(或合并到其中的字典)并用以下内容包装它:

    <Style TargetType="{x:Type local:MyBullet}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate
            ...
        </Setter.Value>
      </Setter>
    </Style>
    

    如果你这样做,你可以使用:

    <local:MyBullet>
      <TextBox />
    </local:MyBullet>
    

    在您的应用程序中的任何位置。

    【讨论】:

    • 我知道这已经过去了 10 年,但对于那些可能仍在 WPF 中工作的人 sigh 它应该是 DefaultStyleKeyProperty,而不是 DefaultStyleKey: DefaultStyleKeyProperty.OverrideMetadata(typeof(MyBullet ), new FrameworkPropertyMetadata(typeof(MyBullet)));
    【解决方案2】:

    Bullet 不是依赖属性,因此无法设置样式。

    但您当然可以声明自己的派生自 Decorator 的类并在构造函数中设置 Bullet,这样您就可以编写:

    <local:MyDecorator>
      <TextBlock />
    </local:MyDecorator>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2017-05-23
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      相关资源
      最近更新 更多