Oto Shavadze
Oto Shavadze

Reputation: 42853

Use variable value as x:Name

I have a button called myBtn. in XAML: ( <Button x:Name="myBtn" ... )

I have also a variable, which value is myBtn

Now, I need change this button's color:

public string buttonName = "myBtn";

private void method () 
{
     this.buttonName.Background = new SolidColorBrush(Color.FromRgb(255, 0, 255));
}

This gives error:

string does not contain definition for Background

What is right syntax to do this?

Upvotes: 0

Views: 1051

Answers (3)

Frank Ibem
Frank Ibem

Reputation: 834

myBtn.Background = new SolidColorBrush(Color.FromRgb(255, 0, 255));


Once you give the control the x:Name attribute, you can refer to it directly from code behind without doing anything else.

Upvotes: 3

Salah Akbari
Salah Akbari

Reputation: 39966

Try this:

public Button buttonName;

private void method ()
{
   buttonName = this.FindName("myBtn") as Button;
   buttonName.Background = new SolidColorBrush(Color.FromRgb(255, 0, 255));
}

Upvotes: 3

E. Moffat
E. Moffat

Reputation: 3288

You can access the background color of a named XAML button by using

myBtn.Background = new SolidColorBrush(Color.FromRgb(255, 0, 255));

The name you specify becomes a Button object for the code-behind in the application you are building.

Upvotes: 2

Related Questions