0

我有一段代码示例,它假设从转换器设置矩形的宽度。我可以看到转换器被调用了两次(第二次使用所需的值),但该值似乎没有达到矩形的 Width 属性。

注意:我故意使用矩形而不是进度条 - 要求

这是xml

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viewmodel="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <viewmodel:CalcWidthFromPercentageConverter x:Key="CalcWidthFromPercentageConverter" />
</Window.Resources>
<Window.DataContext>
    <viewmodel:ViewModel/>
</Window.DataContext>
<Grid>
    <Border x:Name="borderParent" Height="20" HorizontalAlignment="Stretch" BorderBrush="Black" BorderThickness="1" VerticalAlignment="Center">
        <Rectangle Fill="Red" Height="20" HorizontalAlignment="Left">
            <Rectangle.Width>
                <MultiBinding Converter="{StaticResource CalcWidthFromPercentageConverter}">
                    <Binding Path="ProgressWidthPercentage"/>
                    <Binding Path="ActualWidth" ElementName="borderParent"></Binding>
                </MultiBinding>
            </Rectangle.Width>
        </Rectangle>
    </Border>
</Grid>

这是转换器

public class CalcWidthFromPercentageConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values.Count() == 2)
        {
            decimal inputPercentage = (decimal)values[0];
            decimal borderWidth = System.Convert.ToDecimal(values[1]);
            decimal result = borderWidth * inputPercentage;
            return result;
        }
        return values;
    }

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

最后是视图模型

public class ViewModel
{
    private readonly decimal _progressWidthPercentage;

    public decimal ProgressWidthPercentage
    {
        get { return _progressWidthPercentage; }
    }

    public ViewModel()
    {
        _progressWidthPercentage = (decimal)0.37;
    }
}
4

1 回答 1

0

只是解决此问题的“JanW”评论的副本:

“我建议您做两件事:宽度以 Double 测量。使用 Double 而不是 Decimal。更重要的是:不要将“值”作为默认值返回,因为它不提供有效的 Double 值,而是 object[]。这会导致绑定失败”

我只需要将值绑定并在转换器中返回为双精度而不是十进制。

于 2013-08-15T08:25:45.333 回答