0

我正在努力学习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; }
}
4

1 回答 1

0

例外是由于DataContext.SelectedCar.IsPowerAvailable无法访问,请确保该SelectedCar属性确实可以从ScrollViewerDataContext 访问,这里是一个工作示例

 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>

并且 selectedCar 在 VM/CodeBhind 中定义:

private Car _selectedCar = new Car()
    {
        IsPowerAvailable = true,
        PowerValue = 14
    };
    public Car SelectedCar
    {
        get
        {
            return _selectedCar;
        }

        set
        {
            if (_selectedCar == value)
            {
                return;
            }

            _selectedCar = value;                
        }
    }
于 2016-01-25T09:55:05.220 回答