CommandParameter MultiBinding returns array with null elements

Viewed 192
<Button Margin="222,256,130,19" Content="Add" Command="{Binding AddCustomer}">
   <Button.CommandParameter>
      <MultiBinding Converter="{StaticResource MyMultiConverter}">
         <Binding ElementName="Name" Path="Text"></Binding>
         <Binding ElementName="ID" Path="Text"></Binding>
      </MultiBinding>
   </Button.CommandParameter>
</Button>
public class MultiConverter : IMultiValueConverter
{
   public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
   {
      return values;
   }

   // ...
}

I've implemented IMultiValueConverter interface in my Class and Implemented the method Convert, but

When my button command executes the method "AddCustomer" it results in the command parameter ending up as object[] { null, null }.

I haven't found an explanation as to why I have to put return values.Clone(); in order to fix this issue

1 Answers

Does the binding return null (as your title claimed before my edit) or does it return a two-element array { null, null } (as your post claims)? The former seems unlikely. The latter can happen if the individual bindings are incorrect.

But, the other thing that will happen is if you are actually returning the values array, that's not an array you own, nor can rely on. As an optimization, WPF reuses the same array each time the converter is called, and the elements of the array are cleared after the converter returns.

That cloning the array fixes the problem is consistent with this behavior. The answer is very simple: don't try to use that array; it's not yours. If you want all the values verbatim, you have to copy to a new array, just as you're doing now.

Related