我正在尝试学习MultiBinding
.我尝试将两个值(一个double
和一个boolean
)从视图模型传递到转换器,并返回一个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
?
编辑:
视图模型如下所示
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; }
}
例外是由于无法访问DataContext.SelectedCar.IsPowerAvailable
,请确保确实可以从 ScrollViewer
DataContext 访问 SelectedCar
属性,这里是一个工作示例
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<wpfApplication12:MyValueConverter x:Key="MyValueConverter"/>
</Window.Resources>
<Grid>
<ScrollViewer>
<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>
</ScrollViewer>
</Grid>
并且所选的 Car 在 VM/CodeBhind 中定义:
private Car _selectedCar = new Car()
{
IsPowerAvailable = true,
PowerValue = 14
};
public Car SelectedCar
{
get
{
return _selectedCar;
}
set
{
if (_selectedCar == value)
{
return;
}
_selectedCar = value;
}
}