将网格列宽度设置为键百分比

时间:2013-05-16 20:00:01

标签: wpf xaml datatemplate itemscontrol ivalueconverter

我希望根据绑定数据源显示带有动态Rectangle的{​​{1}}。我最初考虑使用Width,但无法绑定到转换器参数以获得读取动态宽度。

我最近的尝试是将父列绑定到UtilPct属性,这是我的BrokerCredit对象中的小数。我认为这是使用十进制值作为绝对值而不是百分比显示。

我该怎么做呢?我希望我的Converter或父列根据UtilPct中的百分比占据总列宽的百分比。我还是WPF的新手,所以我感谢任何帮助!提前谢谢。

XAML:

Rectangle

1 个答案:

答案 0 :(得分:2)

您可以使用IMultiValue转换器,这样您就可以传入WidthPrecentage,以便计算列的宽度。

示例:

转换器:

public class PercentageConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (values[0] is double && values[1] is double)
        {
            return (((double)values[0]) / 100) * ((double)values[1]);
        }
        return values[0];
    }

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

的Xaml:

<Rectangle Width="auto" Fill="Green" Height="20" Grid.Row="0" Grid.Column="1">
    <Rectangle.Width>
        <MultiBinding Converter="{StaticResource PercentageConverter}">
            <Binding Path="Width" />
            <Binding Path="UtilPct" />
        </MultiBinding>
    </Rectangle.Width>
</Rectangle>
相关问题