我有一段代码示例,它假设从转换器设置矩形的宽度。我可以看到转换器被调用了两次(第二次使用所需的值),但该值似乎没有达到矩形的 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;
}
}