代码之家  ›  专栏  ›  技术社区  ›  Josh G

如何基于依赖属性交换控件?

  •  1
  • Josh G  · 技术社区  · 15 年前

    我正在创建自定义控件。

    我希望此控件的模板基于名为CanExpand的依赖属性的值对根控件使用不同的控件。CanExpand是在自定义控件类中定义的。

    如果CanExpand为true,我希望使用Expander显示:

    <ControlTemplate ...>
       <Expander ...>
          <!--...-->
          <ContentPresenter/>
       </Expander>
    </ControlTemplate>
    

    如果canExpand为false,我希望使用HeaderedContentControl显示:

    <ControlTemplate ...>
       <HeaderedContentControl ...>
          <!--...-->
          <ContentPresenter/>
       </HeaderedContentControl>
    </ControlTemplate>
    

    我曾想过使用DataTemplateSelector,但这是一个ControlTemplate,而不是一个DataTemplate,并且没有控件模板的Selector属性。

    我不能用触发器将不同的控件设置为可见/隐藏,因为子内容只能在一个控件下生存。另外,我认为您不能使用触发器更改内容属性。

    有什么建议吗?

    谢谢。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Drew Marsh    15 年前

    在样式内部,将ControlTemplate属性设置为默认状态,然后使用触发器将ControlTemplate属性设置为其他模板。例如:

    <Style ...>
        <Setter Property="ControlTemplate">
            <ControlTemplate ...>    
            </ControlTemplate>
        </Setter>
        <Style.Triggers>
            <Trigger Property="YourProperty" Value="WhateverValue">
                <Setter Property="ControlTemplate">
                    <ControlTemplate ...>
                    </ControlTemplate>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
    

    请记住,对于多个值,可以在同一属性上使用触发器,每个值都会得到完全不同的模板。