是否可以在 XAML 中动态向按钮添加事件?
我是 WPF/XAML 新手,所以请耐心解答菜鸟问题。
我设计了一个控制面板,最终将用作我的网站的后端,并且刚刚使用 TabControl 元素完成了选项卡中所有按钮的布局。 (这是使用 Visual Studio“窗口”表单设计的。
我的问题是,是否可以在 xaml.cs 文件中创建一个函数,该函数将动态处理所有按钮元素的特定事件?例如...
我有30 多个按钮,并且不想在 C# 代码中使用 30 个不同的 Click="btnCustomers_click" + 它们各自的函数。我想要的是一个函数,该函数允许我单击任何按钮,然后根据选择的按钮打开一个新窗口。
下面的代码是我当前的设计,但是对于 30 多个按钮,它们将有很多功能,而且会很混乱,因此我希望有一个功能根据单击的按钮来控制打开哪个窗口。
private void btnMerchants_click(object sender, RoutedEventArgs e)
{
var newWindow = new frmMerchants();
newWindow.Show();
}
提前感谢您提供的任何建议。 !!:)
I am new to WPF/XAML so please bear with the noob question.
I have designed a control panel that will eventually function as a backend for my website, and have just finished laying out all the buttons in tabs using TabControl element. (this is designed using the Visual Studio 'Window' forms.
My question is, is it possible to create a function in the xaml.cs file that will dynamically handle a specific event for all my button elements ? for example...
I have 30+ buttons and dont want 30 different Click="btnCustomers_click" + their respective functions in the c# code. What I desire is say one function that would allow me to click any button and then open a new window depending on which button was selected.
The below code is my current design however for 30+ buttons their will be alot of functions and it will be messy, hence my desire to have one function control which window is opened depending on which button is clicked.
private void btnMerchants_click(object sender, RoutedEventArgs e)
{
var newWindow = new frmMerchants();
newWindow.Show();
}
Thanks in advance for any advice given!! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以为此使用样式:
如果您在没有
x:Key
的资源中设置此样式,它将应用于所有按钮。例如,如果您有一个网格并且您希望将某种样式应用于其中的所有按钮,您可以这样定义它:
如果您只想将其应用于某些按钮,请设置
x:Key
和引用样式:通常,您应该将多次出现的任何属性重构为样式,以防止重复代码。
另外,由于您是初学者,可能会对以下文章感兴趣:
样式和模板
资源概述
You could use a style for this:
If you set this up in the resources somewhere without an
x:Key
it will apply to all buttons.e.g. if you have a Grid and you want a certain style to apply to all Buttons in it you would define it like this:
If you just want to apply it to some buttons set the
x:Key
and reference the style:In general you should refactor any attributes that occur more than once into a style to prevent duplicate code.
Also, since you are a beginner the following articles might be of interest:
Styling and Templating
Resources Overview
您可以在父容器上使用路由事件。
示例:
在后面的代码中:
您可以在 MSDN 上阅读更多相关信息。
You can use routed events on the parent container.
Example:
In the code behind:
You can read more about it on MSDN.
只需将完全相同的 Click="btnCustomers_click" 处理程序(具有通用函数名称)分配给所有按钮即可。然后在函数中根据发件人姓名打开正确的窗口。
Just assign the exact same Click="btnCustomers_click" handler (with a general function name) to all the buttons. Then in the function open the correct window based on the sender's Name.