我想制作几个具有相同点击功能但参数不同的按钮。像这样
XAML:
<Button Click="MyClickFunction(1)" Content="MyFunc(1)"/>
<Button Click="MyClickFunction(2)" Content="MyFunc(2)"/>
<Button Click="MyClickFunction(3)" Content="MyFunc(3)"/>
<Button Click="MyClickFunction(4)" Content="MyFunc(4)"/>
C#:
private void MyClickFunction(object sender, RoutedEventArgs e, int myParam)
{
//do something with parameter e.g. MessageBox.Show()
MessageBox.Show(myParam.ToString());
}
如何在xaml标签中传递参数,否则我将不得不采取其他方式?
答案 0 :(得分:5)
在按钮中使用Tag
属性。像这样:
<Button Click="MyClickFunction" Tag="1" Content="MyFunc(1)"/>
<Button Click="MyClickFunction" Tag="2" Content="MyFunc(2)"/>
<Button Click="MyClickFunction" Tag="3" Content="MyFunc(3)"/>
<Button Click="MyClickFunction" Tag="4" Content="MyFunc(4)"/>
在后面的代码中:
private void MyClickFunction(object sender, RoutedEventArgs e)
{
var tag = ((Button)sender).Tag;
MessageBox.Show(tag.ToString());
}