多重绑定不起作用 - 路径的StrokeThickness不变

时间:2017-12-13 09:34:03

标签: c# wpf multibinding imultivalueconverter

我有ItemsControl ItemsSource填充ObservableCollection路径。实现INotifyPropertyChanged的Path类具有名为StrokeThickness的属性:

private double _strokeThickness;
public double StrokeThickness
{
    get { return _strokeThickness; }
    set
    {
        _strokeThickness = value;
        OnPropertyChanged(nameof(StrokeThickness));
    }
}

在我们的ViewModel中,我们有:

public ObservableCollection<Path> PathCollection
{
    get { return _pathCollection; }
    set
    {
        _pathCollection = value;
        OnPropertyChanged(nameof(PathCollection));
    }
}

这是我的观点:

<!-- Paths -->
<ItemsControl ItemsSource="{Binding PathCollection}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Path Stroke="{Binding Stroke}"
                  Data="{Binding Data}">
                <Path.StrokeThickness>
                    <MultiBinding Converter="{StaticResource    
                        CorrectStrockThiknessConvertor}">
                        <MultiBinding.Bindings>
                            <Binding Source="{Binding
                                StrokeThickness}"></Binding>
                            <Binding ElementName="RootLayout" 
                                Path="DataContext.ZoomRatio" >
                            </Binding>
                        </MultiBinding.Bindings>
                    </MultiBinding>
                </Path.StrokeThickness>
            </Path>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas x:Name="Canvas"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

我使用Multibinding Convertor根据ZoomRatio给出了真正的StrokeThickness。每次地图缩放时都会计算ZoomRatio。

这是我的MultiBinding转换器:

public class CorrectStrockThiknessConvertor : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values != null & values.Length == 2 && (double)values[0] != 0)
        {
            return (double)values[1] / (double)values[0];
        }
        return 1;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

当我跟踪此转换器时,它的工作正常但每次它的StrokeThikness的输入数据都是相同的,这意味着返回值不会改变路径的StrokeThikness。

我做错了吗?

1 个答案:

答案 0 :(得分:1)

MultiBinding中的第一个绑定是错误的。它应该是这样的:

<MultiBinding.Bindings>
    <Binding Path="StrokeThickness" />
    <Binding ElementName="RootLayout" Path="DataContext.ZoomRatio" />
</MultiBinding.Bindings>

同时检查属性名称是否正确,因为您在问题中经常写StrokeThikness而不是StrokeThickness

您还应该检查转换器代码。您似乎将ZoomRatio除以StrokeThickness,我的理解应该是相反的。