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

如何在C#代码中实现WPF附加属性的嵌套属性绑定?

在C#代码中创建绑定读取附加属性的嵌套属性

你可以通过构造PropertyPath来对应XAML中的路径写法,直接在C#代码里创建并应用绑定,以下是两种实用实现方式:

方式一:使用字符串路径(和XAML写法一致)

直接把XAML里的Path字符串搬到C#的PropertyPath构造中,代码示例:

// 实例化绑定对象
var textBinding = new Binding();
// 设置路径,完全对应XAML中的Path格式
textBinding.Path = new PropertyPath("(myns:MyDependencyObject.MyAttachedProperty).NestedProperty");
// 设置绑定模式为OneWay
textBinding.Mode = BindingMode.OneWay;

// 将绑定应用到目标控件的属性(这里以TextBlock的Text属性为例)
BindingOperations.SetBinding(yourTextBlock, TextBlock.TextProperty, textBinding);

注意:字符串里的myns要替换成实际的命名空间全称,或者确保代码文件已经引用了该命名空间。

方式二:类型安全的构造方式(推荐)

通过获取附加属性的DependencyProperty对象来构造路径,避免字符串拼写错误,代码示例:

// 获取目标附加属性的DependencyProperty实例
var targetAttachedProp = MyDependencyObject.MyAttachedProperty;
// 构造路径:先指向附加属性,再拼接嵌套属性名
var propertyPath = new PropertyPath($"{targetAttachedProp}.NestedProperty");

// 创建绑定并配置
var textBinding = new Binding
{
    Path = propertyPath,
    Mode = BindingMode.OneWay
};

// 应用绑定到控件
BindingOperations.SetBinding(yourTextBlock, TextBlock.TextProperty, textBinding);

如果你的绑定需要指定数据源(比如不是继承DataContext),可以直接设置textBinding.Source属性,和XAML中设置Source属性的逻辑一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:27:08