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

WPF GridLength依赖属性报错:无法从System.String转换

问题描述

我正在开发一款WPF应用,编写了如下UserControl:

public partial class MyUserControl : UserControl
{
    public GridLength IconColumnWidth
    {
        get { return (GridLength)GetValue(IconColumnWidthProperty); }
        set { SetValue(IconColumnWidthProperty, value); }
    }

    public static readonly DependencyProperty IconColumnWidthProperty =
        DependencyProperty.Register(nameof(IconColumnWidth), typeof(GridLength), typeof(MyUserControl), new PropertyMetadata(new GridLength(0), new PropertyChangedCallback(SetIconColumnWidth)));

    public static void SetIconColumnWidth(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MyUserControl target = (MyUserControl)d;
        target.MainGrid.ColumnDefinitions[0].Width = ((GridLength)e.NewValue);
    }
}

使用该控件时,我写了这段XAML代码:

<MyUserControl x:Name="Total" Value="{Binding TotalCycles, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" IconColumnWidth="50"  />

此时出现错误提示:TypeConverter cannot convert from System.String。我尝试在DependencyProperty字段上添加[TypeConverter(typeof(GridLengthConverter))]属性,但问题仍未解决,请问哪里操作有误?

问题原因与解决方法
  • 错误原因:你把TypeConverter特性加错了位置。WPF依赖属性的类型转换器需要标注在CLR属性上,而非静态的DependencyProperty字段上。
  • 解决步骤:
    1. 移除DependencyProperty字段上的[TypeConverter(typeof(GridLengthConverter))];
    2. 将该特性移到IconColumnWidth这个CLR属性上;
    3. 额外说明:WPF默认已经为GridLength类型注册了GridLengthConverter,你甚至可以不用手动添加这个特性——只要确保XAML中的值格式合法(比如直接写50对应像素单位,或Auto、*这类标准值即可)。

修改后的CLR属性代码示例:

[TypeConverter(typeof(GridLengthConverter))]
public GridLength IconColumnWidth
{
    get { return (GridLength)GetValue(IconColumnWidthProperty); }
    set { SetValue(IconColumnWidthProperty, value); }
}

public static readonly DependencyProperty IconColumnWidthProperty =
    DependencyProperty.Register(nameof(IconColumnWidth), typeof(GridLength), typeof(MyUserControl), new PropertyMetadata(new GridLength(0), SetIconColumnWidth));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:43:10