Brendan
Brendan

Reputation: 107

How to use functions with parameters as event handlers?

I am using Blend (and I'm very new to it) to create XAML. I have a line of code which calls the function writeC below:

<Button x:Name="key_c" Content="c" HorizontalAlignment="Left" Height="60" 
    Margin="243,188.667,0,0" VerticalAlignment="Top" Width="60" FontWeight="Bold"
    FontFamily="Century Gothic" FontSize="21.333" Foreground="Black" 
    Click="writeC">

This works fine. However, I would like to change it to call a function WriteChar with the parameters "a" and "A", so that it calls the following C# function:

private void writeChar(string myCharCaps, string myCharLower)

How would I write this in XAML?

Upvotes: 5

Views: 5786

Answers (2)

Adi Lester
Adi Lester

Reputation: 25211

You could use a command and a command parameter instead of an event handler:

ViewModel:

public ICommand MyCommand { get; private set; }

// ViewModel constructor
public ViewModel()
{
    // Instead of object, you can choose the parameter type you want to pass.
    MyCommand = new DelegateCommand<object>(MyCommandHandler);
}

public void MyCommandHandler(object parameter)
{
    // Do stuff with parameter
}

XAML:

<Button Command="{Binding MyCommand}" CommandParameter="..." />

You can read more about commands in WPF here.

Of course, if you want the button to always execute the code with the same parameters, then passing parameters from the button doesn't have any meaning, and those parameters could be hard coded into the handler:

<Button Click="Button_Click" />

private void Button_Click(object sender, EventArgs e)
{
    WriteChar("a", "A");
}

Upvotes: 2

Scott Jones
Scott Jones

Reputation: 2906

Your click handler needs to abide by the event handler signature. If you want to make that handler a simple wrapper around your WriteChar, that's fine. More info here: http://msdn.microsoft.com/en-us/library/bb531289(v=vs.90).aspx

Upvotes: 4

Related Questions