问题
I want to display a Rectangle
with a dynamic Width
based on a bound data source. I originally looked into using a Converter
, but wasn't able to bind to the converter parameter to get a read dynamic width.
My most recent attempt was binding the parent column to the UtilPct property, which is a decimal in my BrokerCredit object. I think this is using the decimal value as an absolute instead of a percentage display.
How would I go about doing this? I'd like my Rectangle
or the parent column to take up a percentage of the total column width according to the percentage in UtilPct. I'm still pretty new to WPF, so I appreciate any help! Thanks in advance.
XAML:
<ItemsControl x:Name="icBrokerCreditList" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Path=BrokerCreditList}" HorizontalAlignment="Stretch">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"></ColumnDefinition>
<ColumnDefinition x:Name="utilizationColumn" Width="{Binding Path=UtilPct}"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Background="White" Foreground="Black" FontSize="12" Text="{Binding Path=BrokerName}"></TextBlock>
<Rectangle Width="auto" Fill="Green" Height="20" Grid.Row="0" Grid.Column="1">
<!--"{Binding Converter={StaticResource PercentageConverter},
ElementName=utilizationColumn, Path=Width, ConverterParameter=.1}"-->
</Rectangle>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
回答1:
You could use IMultiValue
converter, this way you can pass in the Width
and the Precentage
so you can calculate the width of the column.
Example:
Converter:
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>
来源:https://stackoverflow.com/questions/16596377/set-grid-column-width-to-bound-perctange