Wpf:实现IValueConverter

时间:2019-02-28 15:31:22

标签: c# wpf

“ System.Collections.Generic.List`1 [System.Double]”类型的对象不能转换为“ System.IConvertible”类型。 我正在实现IValueConverter的类中遇到此异常。这是该类的方法。我还共享了计算属性Mymargin的方法,该属性在Converter类中引发异常。

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    return new Thickness(0, 0, System.Convert.ToDouble(value), 0);
}

XAML

<ItemsControl ItemsSource="{Binding TimeAxis}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Name="horizontalLabels" Orientation="Horizontal"  />

        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock
                Text="{Binding}" 
                Width="{Binding DataContext.LabelWidth, RelativeSource={RelativeSource AncestorType=ItemsControl}, diag:PresentationTraceSources.TraceLevel=High, UpdateSourceTrigger=PropertyChanged}"  
                Background="Red" Height="30"  FontSize="12"
                Margin="{Binding DataContext.MyMargin, RelativeSource={RelativeSource AncestorType=ItemsControl}, Converter={StaticResource ResourceKey=marginConverter} , diag:PresentationTraceSources.TraceLevel=High, UpdateSourceTrigger=PropertyChanged}" 
            >
            </TextBlock>

        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

C#

public void AddLabels(double lbs)
{
    LabelWidth = new List<double>();
    MyMargin = new List<double>();

    TimeAxis.Clear();

    Counter = 0;
    MinimumMargin = 3;
    MinimumLabelWidth = 27;

    for (double i = 0; i < (ulong)lbs; i++) 
    {
        TimeAxis.Add(Counter.ToString()); 
        var tp = i;
        var numberOfCharacters = (TimeAxis[TimeAxis.Count-1].Length);
        var boxes = (numberOfCharacters / 4.0);

        NumberOfBoxes= (ulong)Math.Ceiling(boxes);
        Counter += (SampleStepSize * NumberOfBoxes) ;

        if (NumberOfBoxes > 1)
        {
            i += (NumberOfBoxes - 1);
        }

        LabelWidth.Add((NumberOfBoxes * MinimumLabelWidth));
        MyMargin.Add((MinimumMargin * NumberOfBoxes));
    }
    if (CanvasWidth > Convert.ToUInt64(TimeAxis.LastOrDefault()))
    {
        TimeAxis.Add(Counter.ToString());
    }

}

0 个答案:

没有答案