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

如何为自定义ComboBox绑定其子样式ToggleButton的GryphlBrush依赖属性

步骤1:修正自定义控件的依赖属性定义

你当前的依赖属性写法不符合WPF规范,会导致依赖属性系统无法正常识别:

  • 依赖属性字段必须遵循[属性名]Property的命名规则,不能自定义后缀为DP
  • CLR属性包装器必须调用GetValue/SetValue操作依赖属性的存储槽,不能自行声明私有字段存储值

修正后的后台代码:

public class BorderedComboBox : ComboBox
{
    public static readonly DependencyProperty GryphlBrushProperty = DependencyProperty.Register(
        nameof(GryphlBrush), typeof(Brush), typeof(BorderedComboBox));
    
    public Brush GryphlBrush
    {
        get => (Brush)GetValue(GryphlBrushProperty);
        set => SetValue(GryphlBrushProperty, value);
    }
}

步骤2:调整箭头Path的绑定路径

当前Path位于ComboBoxToggleButton的控件模板内部,直接写{Binding GryphlBrush}默认会绑定到当前控件的DataContext,无法关联到自定义ComboBox的依赖属性,需要通过相对源向上查找父级BorderedComboBox控件:

<Path x:Name="arrow" 
      Stroke="{Binding GryphlBrush, RelativeSource={RelativeSource AncestorType=components:BorderedComboBox}}" 
      VerticalAlignment="Center" 
      Margin="0" 
      HorizontalAlignment="Center" 
      Fill="{StaticResource ComboBox.Static.Glyph}" 
      Data="F1 M 0,0 L 2.667,2.66665 L 5.3334,0 L 5.3334,-1.78168 L 2.6667,0.88501 L0,-1.78168 L0,0 Z"/>

注意代码中的components命名空间需要和你XAML头部引入BorderedComboBox类的命名空间保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:36:08