-2

I am just starting to program in c# and I don't understand if I really have a problem with the syntax or with WPF, I want to change the text of the button, but I can't do it, if someone can help me, I would appreciate it.

    public MainWindow()
    {
        InitializeComponent();

        Grid mainGrid = new Grid();

        this.Content = mainGrid;

        Button BTN = new Button();
        
        BTN.Width = 175;
        BTN.Height = 23;
        BTN.Margin = new Thickness(0, -30, 0, 0);
        BTN.Click += BTNclick;
        
        WrapPanel BTNwrap = new WrapPanel();
        
        TextBlock BTNtext = new TextBlock();
        
        BTNtext.Text = "Click";
        
        BTNwrap.Children.Add(BTNtext);
        
        BTN.Content = BTNwrap;

        mainGrid.Children.Add(BTN);

    }

    private void BTNclick(object sender, RoutedEventArgs e)
    {
        //BTNtext.Text = "Clicked!";
    }
Pan
  • 3
  • 3
  • 1
    Besides what is said in the answer, creating UI in code behind is considered bad practice in WPF. You should declare those elements in XAML, and simply set `x:Name="BTNtext"` on The TextBlock, which would automatically generate an appropriate field in the MainWindow class. Learning WPF is not done in a day. Consider reading a book like *WPF Unleashed* by Adam Nathan. – Clemens Mar 06 '21 at 08:15

1 Answers1

0

Since you defined your BTNtext TextBlock class in the constructor of your MainWindow, you can't access it in another function. You need to define your BTNtext TextBlock class at the MainWindow class level (outside the constructor):

private TextBlock BTNtext;

In your constructor you create a new instance and assign it to the class member:

BTNtext = new TextBlock();

Then you can access your BTNtext in the click event handler:

private void BTNclick(object sender, RoutedEventArgs e)
{
    BTNtext.Text = "Clicked!";
}

A couple of things I noticed:

  • The Button class has a content property you can use to simply display a text: Content MSDN Docs
  • Once you learned the basics, you should check out the MVVM pattern: MVVM SO
Stefan Koell
  • 1,476
  • 3
  • 15
  • 25