简体   繁体   中英

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"/>

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);

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM