如何在WPF中捕获工具栏项单击事件 [英] How to catch toolbar item click event in WPF

查看:923
本文介绍了如何在WPF中捕获工具栏项单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先对不起,如果答案很明显,但我是WPF的新手。有没有更好的方法从工具栏中获取单击按钮?每个按钮都是其中一个驱动器,因此它们以编程方式添加。问题是,只要我将图像添加到按钮,我的代码就不再起作用了。我确信有一个简易解决方案。



First of all sorry if the answer is obvious but i'm new to WPF. Is there a better way to get the clicked button from toolbar? Every button is one of the drives so they are added programatically. The problem is that as soon i add an image to the buttons my code doesn't work any longer. I'm sure there is one easyer solution.

private void RightDriveToolBar_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    int i = 0;
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        string ButName = e.Source.ToString().Substring(32, 1);

        if (e.Source.ToString().Contains("System.Windows.Controls"))
        {
            foreach (var citem in RightDriveComboBox.Items)
            {
                if (citem.ToString().Substring(0, 1) == ButName)
                {
                    RightDriveComboBox.SelectedIndex = i;
                }
                i++;
            }
        }
    }
}





也是代码对于按钮





also the code for the buttons

Button But = new Button();
StackPanel ButStackPanel = new StackPanel();
Image ButImage = new Image();
TextBlock textBlock1 = new TextBlock();

ButImage.Source = new BitmapImage(new Uri("g:/Reinstall/Icons/105.png"));
ButImage.Width = 16;
textBlock1.TextAlignment = TextAlignment.Center;
textBlock1.Text = drive;

ButStackPanel.Orientation = Orientation.Horizontal;
ButStackPanel.Children.Add(ButImage);
ButStackPanel.Children.Add(textBlock1);

But.Content = ButStackPanel;
LeftDriveToolBar.Items.Add(But);

推荐答案

如果我理解你,你必须添加 RoutedEventHandler [ ^ ]。



If i understand you well, you have to add RoutedEventHandler[^].

Button Btn = new Button();
//set properties here
//...
//and the magic comes here:
Btn.Click += new RoutedEventHandler(ToolbarBtn_Click);

//and the subroutine which 
void ToolbarBtn_Click(object sender, RoutedEventArgs e)
{
    //your code
}





如需了解更多信息,请参阅: WPF:初学者指南:n的第3部分 [ ^ ]


这篇关于如何在WPF中捕获工具栏项单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆