I'm trying to use a Multibinding in combination with a converter with a Button control and Width property in XAML but I can't get it to work.
The converter is:
public class ColumnsToWidthConverter: IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return 40;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
It's hardcoded for 40 now, for testing purposes.
The XAML definition is:
<Button
Height="{Binding ElementName=root,Path=KeyHeight}"
FontSize="{Binding FontSize}"
Content="{Binding Display}"
Command="{Binding ElementName=root, Path=Command}"
CommandParameter="{Binding}"
Style="{StaticResource SelectedButton}">
<Button.Width>
<MultiBinding Converter="{StaticResource ColumnsToWidthConverter}">
<Binding Path="Columns"/>
<Binding Path="KeyHeight" ElementName="root"/>
</MultiBinding>
</Button.Width>
</Button>
The button is rendered from a ListView
and defined in the ListView.ItemTemplate
. When debugging the application, the converter is passed and the value of 40 is returned. The object[] values
parameter contains the correct values passed in the MultiBinding paths. However, the width of the button is set to its content and not the 40 as in the example above.
The ColumnsToWidthConverter
is defined in the parent ListView.Resources
<converter:ColumnsToWidthConverter x:Key="ColumnsToWidthConverter"/>
When I remove the MultiBinding and set the Width property to 40 in the XAML definition, the button is rendered correctly.
The root
element is the usercontrol itself and KeyHeight
is a DependencyProperty
.
How do I set the button width using the multibinding?
The issue does not come from the multibinding but from the converter itself. When implementing a converter, you are expected to return the same type of value as expected by the control (there's no implicit conversion since you're the one implementing the converter). In this case, the Width
property is a double
, so you should return a value of the same type:
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return 40d;
}