5

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?

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Brendan
  • 107
  • 2
  • 13

2 Answers2

4

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

Scott Jones
  • 2,880
  • 13
  • 19
  • Ok, I still don't quite get it. I read through the instructions, but I'm still a little lost. Sorry... I'm very new to XAML and C#. – Brendan Jun 04 '13 at 18:56
  • Not sure how to help you. If you're confused about writing the function itself, you can do that in XAML, but it's far easier to implement the logic in a code behind file (like C# or VB.NET). – Scott Jones Jun 04 '13 at 18:59
  • 2
    the easiest way to get the right signature is in the xaml editor, to type "Click=", and it should pop up auto completion like "new event handler", and just press enter. it will give it a name, and create the method with the correct signature in the code file. – John Gardner Jun 04 '13 at 19:07
  • Hmm... this process doesn't seem to autocomplete. Do I have to install something or enable something? – Brendan Jun 06 '13 at 21:08
2

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");
}
Adi Lester
  • 24,731
  • 12
  • 95
  • 110