Search code examples
c#xamluwpcomputer-science

UWP Pass Extra Parameter To Method From XAML


I have a StackPanel and, when it loads, I want to put some textboxes inside it programmatically. The number of textboxes must be passed when the function is called.

XAML

<StackPanel x:Name="RFC" Orientation="Horizontal" Loaded="{x:Bind m:Formas.CrearCuadrosForma}"/>

I'm trying to do it like this:

CS

public static void CrearCuadrosForma(object sender, RoutedEventArgs e, int cantidad)
{
    //TODO
}

But when i put a parameter in the XAML code like this

Loaded="{x:Bind m:Formas.CrearCuadrosForma(13)}"

I get the error: "Cannot find a function overload that takes 1 parameters" and I can't find a way to send the "object sender" and "RoutedEventArgs e" as parameters or another way to send the "int cantidad" to the function...

Any thoughts?

Cheers!


Solution

  • I get the error: "Cannot find a function overload that takes 1 parameters" and I can't find a way to send the "object sender" and "RoutedEventArgs e" as parameters or another way to send the "int cantidad" to the function

    It's not suitable that redirecting Loaded event to specific method with x:Bind. For your scenario the better way is using XamlBehaviors to detect Loaded event then invoke specific command with paramter.

    For examle:

    <Grid>
        <Grid.Resources>
            <x:Int32 x:Key="Parameter">15</x:Int32>
        </Grid.Resources>
        <interactivity:Interaction.Behaviors>
            <Interactions:EventTriggerBehavior EventName="Loaded">
                <Interactions:InvokeCommandAction Command="{x:Bind LoadedCommand}" CommandParameter="{StaticResource Parameter}" />
            </Interactions:EventTriggerBehavior>
        </interactivity:Interaction.Behaviors>
    </Grid>
    

    code behind

    public class CommadEventHandler<T> : ICommand
    {
        public event EventHandler CanExecuteChanged;
    
        public Action<T> action;
        public bool CanExecute(object parameter)
        {
            return true;
        }
    
        public void Execute(object parameter)
        {
            this.action((T)parameter);
        }
        public CommadEventHandler(Action<T> action)
        {
            this.action = action;
    
        }
    }
    public ICommand LoadedCommand
    {
        get
        {
            return new CommadEventHandler<int>((s) => LoadedCommandFun(s));
        }
    }
    private void LoadedCommandFun(int s)
    {
    
    }