I have a piece of code sample which suppose to set the width of the rectangle from a converter. I can see the converter is called twice (the second time with the required value) but the value does not seem to reach the Width property of the rectangle.
note: I use rectangle on purpose instead of a progressbar - requirements
Here is the xaml
<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>
here is the converter
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 };
}
}
and last the viewmodel
public class ViewModel
{
private readonly decimal _progressWidthPercentage;
public decimal ProgressWidthPercentage
{
get { return _progressWidthPercentage; }
}
public ViewModel()
{
_progressWidthPercentage = (decimal)0.37;
}
}
Just a copy of "JanW" comment which solved this:
"Two things i would suggest you: Width is measured in Double. Use Double instead of Decimal. More important: do not return "values" as default, since it does not deliver a valid Double value, instead object[]. This would cause the binding to fail"
I just had to turn the value binding and returned in the converter to double instead of decimal.