You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF自定义ContentControl:如何声明式根据IconContent设置Border宽度?

用声明式方式实现WPF自定义控件动态设置Border宽度

你可以通过在XAML中添加**触发器(Trigger)**来实现这个需求,完全不需要修改后台代码,以下是两种可行的方案:

方案一:在ControlTemplate中添加DataTrigger

给目标Border命名,然后在ControlTemplate.Triggers中添加触发器,根据IconContent是否为空动态修改Width属性:

<Style TargetType="{x:Type views:DialogCustomControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type views:DialogCustomControl}">
                <Grid>
                    <!-- 给Border命名,方便触发器定位 -->
                    <Border x:Name="IconContainer" Width="40">
                        <ContentPresenter Content="{TemplateBinding IconContent}" />
                    </Border>
                </Grid>
                <ControlTemplate.Triggers>
                    <!-- 绑定模板父级的IconContent,值为null时设置Width为0 -->
                    <DataTrigger Binding="{Binding IconContent, RelativeSource={RelativeSource TemplatedParent}}" Value="{x:Null}">
                        <Setter TargetName="IconContainer" Property="Width" Value="0"/>
                    </DataTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

方案二:给Border单独定义带触发器的Style

把Border的样式逻辑抽离出来,通过绑定父级自定义控件的IconContent属性实现动态切换:

<Style TargetType="{x:Type views:DialogCustomControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type views:DialogCustomControl}">
                <Grid>
                    <Border>
                        <Border.Style>
                            <Style TargetType="Border">
                                <!-- 默认Width设为40 -->
                                <Setter Property="Width" Value="40"/>
                                <Style.Triggers>
                                    <!-- 向上查找自定义控件,绑定IconContent属性 -->
                                    <DataTrigger Binding="{Binding IconContent, RelativeSource={RelativeSource AncestorType={x:Type views:DialogCustomControl}}}" Value="{x:Null}">
                                        <Setter Property="Width" Value="0"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Border.Style>
                        <ContentPresenter Content="{TemplateBinding IconContent}" />
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

注意事项

  • 触发器中不能直接使用TemplateBinding,所以需要通过RelativeSource={RelativeSource TemplatedParent}或者AncestorType来绑定目标属性。
  • 两种方案都是纯声明式实现,完全符合你的需求,不需要额外编写依赖属性的后台逻辑。

内容的提问来源于stack exchange,提问作者Boppity Bop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 07:53:15