Search code examples
c#xamluwpwinui

x:Bind call function with params object[] and pass n parameters


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'


Solution

  • 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.