我正在努力学习MultiBinding
。我尝试将两个值(一个double
和一个boolean
)从 viewmodel 传递给转换器并返回string
结果。
XAML
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource MyValueConverter}">
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ScrollViewer}" Path="DataContext.SelectedCar.PowerValue" />
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ScrollViewer}" Path="DataContext.SelectedCar.IsPowerAvailable" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
转换器
class MyValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (System.Convert.ToBoolean(values[1]))
{
return string.Format("{0:n1}", values[0]);
}
else
{
return "[not available]";
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
视图模型
public double PowerValue
public bool IsPowerAvailable
在转换器中我会得到一个异常Unable to cast object of type 'MS.Internal.NamedObject' to type 'System.IConvertible
。
这是什么意思?我是否执行MultiBinding
不正确?
编辑:
ViewModel 看起来像这样
class CarViewModel : ViewModelBase
{
private car _selectedCar;
public car SelectedCar
{
get { return _selectedCar; }
set
{
_selectedCar = value;
}
}
模型如下所示:
class car
{
public double PowerValue { get; set; }
public bool IsPowerAvailable{ get; set; }
}