Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C#
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

C#
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);
Posted

1 solution

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

C#
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
}


For further information, please see: WPF: A Beginner's guide: Part 3 of n[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900