C# 多重绑定-指定的强制转换无效
下面的代码绑定列宽:C# 多重绑定-指定的强制转换无效,c#,wpf,xaml,casting,multibinding,C#,Wpf,Xaml,Casting,Multibinding,下面的代码绑定列宽:Samp1.ActualWidth和Samp2.ActualWidth到StatName.Width。见: 但是,设计器报告错误指定的强制转换无效。,但尽管出现错误,代码仍按预期编译和执行 尽管它按预期运行,但“错误”仍然让我感到困扰 问题:导致错误的原因:指定的强制转换无效。?什么被投给了什么?我怎样才能修好它?如果修复不简单,我如何至少隐藏或忽略错误 注意:问题类似。但是,该代码会导致运行时异常,而我的代码会导致生成错误并正常运行(不会引发任何异常) Xaml: 在任何转
Samp1.ActualWidth
和Samp2.ActualWidth
到StatName.Width
。见:
但是,设计器报告错误指定的强制转换无效。
,但尽管出现错误,代码仍按预期编译和执行
尽管它按预期运行,但“错误”仍然让我感到困扰
问题:导致错误的原因:指定的强制转换无效。
?什么被投给了什么?我怎样才能修好它?如果修复不简单,我如何至少隐藏或忽略错误
注意:问题类似。但是,该代码会导致运行时异常,而我的代码会导致生成错误并正常运行(不会引发任何异常)
Xaml:
在任何转换器中,您应该始终期望值可以是
dependencProperty.UnsetValue
。当由于任何原因无法获得实际值时,wpf使用该值。最常见的情况是绑定无法解析(例如,绑定到不存在的属性)。WPF设计器不会编译整个代码,因此可能会出现错误行为,尤其是在绑定时。请注意,null
不能代替UnsetValue
,因为null
可以是有效值。因此,请期待unset value
,如果可能的话,尝试在这种情况下做一些有意义的事情。例如:
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double totalWidth = 0;
foreach (double Width in values.OfType<double>())
totalWidth += Width;
DataGridLength outLen = new DataGridLength(totalWidth);
return outLen;
}
公共对象转换(对象[]值,类型targetType,对象参数,System.Globalization.CultureInfo区域性)
{
双总宽度=0;
foreach(值的两倍宽度。of type())
总宽度+=宽度;
DataGridLength outLen=新的DataGridLength(总宽度);
返回输出;
}
这将忽略所有非双精度的值(包括
未设置的值
)。检查转换器中值数组中项目的类型。很可能其中一些是dependencProperty.unset值,而不是double。要测试-更改为foreach(value.OfType()的宽度为两倍)。我再次检查未设置的值。这是第一次遇到的最意想不到的事情。也可能是由于您的ConvertBack
引起的。如果您实际上没有使用它来转换回,通常最好让它抛出NotSupportedException
public class WidthConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double totalWidth = 0;
foreach (double Width in values)
totalWidth += Width;
DataGridLength outLen = new DataGridLength(totalWidth);
return outLen;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return new object[] { DependencyProperty.UnsetValue, DependencyProperty.UnsetValue};
}
}
public class MyGenericRecord
{
public string a { get; set; }
public string b { get; set; }
public string c { get; set; }
}
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double totalWidth = 0;
foreach (double Width in values.OfType<double>())
totalWidth += Width;
DataGridLength outLen = new DataGridLength(totalWidth);
return outLen;
}