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字段上。 - 解决步骤:
- 移除DependencyProperty字段上的
[TypeConverter(typeof(GridLengthConverter))]; - 将该特性移到
IconColumnWidth这个CLR属性上; - 额外说明:WPF默认已经为
GridLength类型注册了GridLengthConverter,你甚至可以不用手动添加这个特性——只要确保XAML中的值格式合法(比如直接写50对应像素单位,或Auto、*这类标准值即可)。
- 移除DependencyProperty字段上的
修改后的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
相关产品推荐
相关产品推荐

