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?
If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
Event handlers are the JavaScript code that invokes a specific piece of code when a particular action happens on an HTML element. The event handler can either invoke the direct JavaScript code or a function.
Here is the code: var someVar = some_other_function(); someObj. addEventListener("click", function(){ some_function(someVar); }, false);
If a handler function is defined for one of the following events, the handler function behaves like an exception handler and catches the event. In this case no output is generated in the report files and monitor window.
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
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With