How does one add a multibinding to several viewmodel objects in xaml?
I need to bind the IsEnabled
property of a context menu to two integers in my viewmodel. The following binding doesn't work, since its designed for GUI components. How would I do it to work with my ints?
<MenuItem ItemsSource="{Binding MyMenuItem}">
<MenuItem.IsEnabled>
<MultiBinding>
<Binding ElementName="FirstInt" Path="Value" />
<Binding ElementName="SecondInt" Path="Value" />
</MultiBinding>
</MenuItem.IsEnabled>
</MenuItem>
MyMenuItem is CLR object with the two integers, FirstInt and SecondInt.
Filip's answer was acceptable, but for anyone looking for Filip's desired solution, the following should do it:
<MenuItem ItemsSource="{Binding MyMenuItem}">
<MenuItem.IsEnabled>
<MultiBinding Converter="{StaticResource IntsToEnabledConverter}">
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="DataContext.FirstInt" />
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="DataContext.SecondInt" />
</MultiBinding>
</MenuItem.IsEnabled>
</MenuItem>
It should be noted that the AncestorType
on the binding may need to be changed accordingly. I assumed the view model was set as the DataContext
of the window, but the same idea applies to user controls, etc.
For your particular example you need an IMultiValueConverter that will convert the two integers to a boolean value representing whether the menu item is enabled or not. Something like this:
Public Class MVCIntsToEnabled
Implements IMultiValueConverter
Public Function Convert(ByVal values() As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IMultiValueConverter.Convert
If values IsNot Nothing Then
If values.Count = 2 Then
Return (values(0) > 0) AndAlso (values(1) > 0)
Else
Return False
End If
Else
Throw New ArgumentNullException("values")
End If
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetTypes() As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object() Implements System.Windows.Data.IMultiValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class
Used like this:
<local:MVCIntsToEnabled x:Key="IntsToEnabledConverter" />
...
<MenuItem ItemsSource="{Binding MyMenuItem}">
<MenuItem.IsEnabled>
<MultiBinding Converter="{StaticResource IntsToEnabledConverter}">
<Binding ElementName="FirstInt" Path="Value" />
<Binding ElementName="SecondInt" Path="Value" />
</MultiBinding>
</MenuItem.IsEnabled>
</MenuItem>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With