Home > Software engineering >  x:Bind call function with params object[] and pass n parameters
x:Bind call function with params object[] and pass n parameters

Time:01-24

Is it possible to call a helper function in XAML that takes any number of parameters using x:Bind? I have this XAML code:

<Button Content="Button content"
          Margin="0,0,10,0"
          Command="{Binding SomeCommand}"
          IsEnabled="{x:Bind helpers:CommonHelpers.TrueForAll(ViewModel.Property,ViewModel.SomeOtherProperty)}"
          VerticalAlignment="Center"> 
</Button>

where the TrueForAll function looks like this:

public static bool TrueForAll(params object[] objects) => objects.All(x => x != null);

When trying to use this in action with multiple parameters, the compiler says Cannot find a function overload that takes 2 parameters. and when only using one, it expects object[] so it says Expected argument of type 'Object[]', but found 'MyType'

CodePudding user response:

The behavior is related to the params keyword. x:Bind can't recognize params that you defined. It is still looking for method with explicit parameter lists.

My suggestion is that you might need to use List<object> or ObservableCollection<object> as the parameter for the method. And create such a property in your ViewModel as well. This could be accepted by the x:Bind.

CodePudding user response:

Is it possible to call a helper function in XAML that takes any number of parameters using x:Bind?

No.

The solution is to define the method with explicit parameters:

public static bool TrueForAll(IEnumerable<object> objects) 
    => objects?.All(x => x != null) == true;

And create the parameter programmatically:

public IEnumerable<object> Input => 
    new object[] { ViewModel.Property, ViewModel.SomeOtherProperty };

XAML is a markup language and trying to do things like creating arrays in it is an anti-pattern really. You should create the input parameter in the code-behind of the very same view or move your logic to the view model.

  • Related