0

I have a xaml file with buttons like this

<Button Grid.Column="4" BorderThickness="0">3</Button>
<Button Grid.Column="5" BorderThickness="0">4</Button> 

The Problem is I can't manage to control the buttons in C#. I've read about templates and resources and tried it but I am unsure if I did was correct.

Most examples online just have a click function but I wan't full control of the button having all of them in a 2D Array and changing them when I want to.

So How do I point to a button created in the xaml file so that I could do

button.Content = "test"; 

or whatever.

gempir
  • 1,791
  • 4
  • 22
  • 46

4 Answers4

2

You should give a Name to your controls in the XAML like this

<Button Name="FirstButton" Grid.Column="4" BorderThickness="0">3</Button>

Then you'll be able to access it in the code-behind :

FirstButton.Content = "test"
Tom C.
  • 593
  • 4
  • 12
2

All the answers about naming buttons in XAML are right.

<Button x:Name="btn0"/>
<Button x:Name="btn1"/>

Naming components make them public, thus you can easily access to them in the code behind. If you want, you can later create List of buttons and add them one by one. And then just access to the list.

Nikolai Arsenov
  • 464
  • 2
  • 10
  • What is the difference here between x:Name and Name – gempir May 10 '16 at 10:24
  • @danielps1 http://stackoverflow.com/questions/589874/in-wpf-what-are-the-differences-between-the-xname-and-name-attributes – Tom C. May 10 '16 at 10:30
  • If Name is available as a property on the class, Name and x:Name can be used interchangeably as attributes. But, you cannot use both at the same time on the same element. There is no difference. https://msdn.microsoft.com/en-us/library/ms752290.aspx Look at this link – Nikolai Arsenov May 10 '16 at 10:30
1

set in xaml

<Button content="test"/> 

or in code behind

<Button x:Name = "MyButton"/>

MyButton.Content = "Test";
Muds
  • 4,006
  • 5
  • 31
  • 53
1

You just give the button a name and that name you use in code

<Button x:Name="btnBla"/>

btnBla.Background = Brushes.SaddleBrown;
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98