user1005633
user1005633

Reputation: 755

How to use a xaml object in another class

I have one class with a xaml which contains a label. I want to change content of this label from one different class. for example i have a class mainwindow.xaml.cs with mainwindow.xaml and i want to handle the label of mainwindow.xaml from the newclass.cs. How can i do this??

edit: i have this label in a grid and i want to change the content from another class:

<Label Content="" Panel.ZIndex="1" FontWeight="SemiBold" FontSize="16px" Name="lb1" Margin="0,0,0,0" VerticalAlignment="Bottom" Height="30" HorizontalAlignment="Right" Width="250" HorizontalContentAlignment="Right" VerticalContentAlignment="Top"/>

Upvotes: 1

Views: 2590

Answers (3)

Sandeep Bansal
Sandeep Bansal

Reputation: 6394

What I would do is something like this, I'm not sure if it's the most logical thing to do but it works for me.

In your newclass.cs :

Class Newclass
{
     MainWindow main;


     public Newclass(MainWindow win)
     {
         main = win;
         main.label.content = "";
     }
}

and then in your mainwindow.xaml.cs:

Newclass class = new Newclass(this);

Upvotes: 2

Wolfgang Ziegler
Wolfgang Ziegler

Reputation: 1685

Data binding and MVVM would be the most elegant solution. But you can simply use code-behind. Give the label a name <Label x:Name="myLabel"> so you can access it in your code with that name like any other variable. You can then pass this variable to your newclass.cs and change its properties there.

Upvotes: 1

blindmeis
blindmeis

Reputation: 22435

you can use binding - or even better binding with MVVM pattern and viewmodel first.

but nevertheless, when asking a question you should post some code

Upvotes: 0

Related Questions