
[DeepSeek] 。。。(前文的铺垫部分,详见:https://www.php.cn/link/48e3e457e80b2cf856688ab6280c0d56*)
[DLGCY] 你前面说的可能不太准确,实际上只要这样写就可以在 XAML 中使用 Auto 赋值:
[TypeConverter(typeof(LengthConverter))]public static double GetContentWidth(DependencyObject obj){ return (double)obj.GetValue(ContentWidthProperty);}[DeepSeek] 根据您提供的代码和 WPF 的底层机制,以下是对附加属性中
[TypeConverter]
您给出的实现方式完全符合 WPF 设计规范,能够支持
Auto
特性位置正确:
[TypeConverter]
Get
TypeConverter
| 使用场景 | 应标注位置 | 是否生效 | 示例代码 |
|---|---|---|---|
| 附加属性的 Get 方法 | public static double GetXxx() | ✅ 生效 | 您的写法 |
| 附加属性所在类 | 类定义上方 | ❌ 不生效 | \[TypeConverter(...)\] class MyAttached |
| 依赖属性字段 | DependencyProperty 字段 | ❌ 不生效 | \[TypeConverter(...)\] static DependencyProperty |
尽管
LengthConverter
// XAML 中可识别的值形式SetContentWidth(element, Double.NaN); // 对应 "Auto"SetContentWidth(element, 200.0); // 对应 "200" 或 "200px"
"Auto"
Double.NaN
Width="Auto"
"50px"
"30%"
LengthConverter.ConvertFromString()
public class CustomAttached { // 1. 注册附加属性 public static readonly DependencyProperty ContentWidthProperty = DependencyProperty.RegisterAttached( "ContentWidth", typeof(double), typeof(CustomAttached), new FrameworkPropertyMetadata( Double.NaN, // 默认值设为 NaN,支持 Auto 行为 FrameworkPropertyMetadataOptions.AffectsMeasure ) ); // 2. 在 Get 方法上添加 TypeConverter 特性 [TypeConverter(typeof(LengthConverter))] public static double GetContentWidth(DependencyObject obj) { return (double)obj.GetValue(ContentWidthProperty); } // 3. Set 方法无需任何特性 public static void SetContentWidth(DependencyObject obj, double value) { obj.SetValue(ContentWidthProperty, value); }}<textblock></textblock><grid></grid>
例如
FrameworkElement.Height
[TypeConverter(typeof (LengthConverter))]public double Height{ get => (double) this.GetValue(FrameworkElement.HeightProperty); set => this.SetValue(FrameworkElement.HeightProperty, (object) value);}原因在于:
Get/Set
Get
// ❌ 错误:将 TypeConverter 标注在 Set 方法上public static void SetCustomWidth(DependencyObject obj, double value) => obj.SetValue(CustomWidthProperty, value); // ❌ 错误:标注在 DependencyProperty 字段上[TypeConverter(typeof(LengthConverter))] public static readonly DependencyProperty CustomWidthProperty = ...;
✅ 在附加属性中,
[TypeConverter]
"Auto"
Double.NaN
"100px"
"50%"
GridLength
double
NaN
Auto
以上就是又教 DeepSeek 做人了——论 WPF 中 TypeConverter 在附加属性中的应用的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号