简体   繁体   中英

Which is the best way to access to object from another class ex.:MainPage.xaml.cs?

For example I'm using this technique:

XAML
<Button x:Name="playButton" Content="Play with rabbit" With="20" Height="20"/>

MainPage.xaml.cs

public Button _PlayButton
{
 get { return playButton; }
}

PlayerControl.cs

//received instance of MainPage class to "_mainPage"

public Button Play
{
 _mainPage._PlayButton.Content = "Who care about this text?";
 //play logic
}

I'm looking for the best practice. Where I can read deeply about this scope?

There's no best practice. It all depends on your requirements. Approaches I've used in various places for similar tasks:

  1. As said by Ondra — MVVM. However, not every problem needs MVVM.
  2. If PlayerControl owns the text of the play button — you could create a DependencyProperty of type string in the PlayerControl class, and data bind the button text to the property of your control.
  3. If the main page owns the text, however PlayerControl sometimes need to update it — you could expose an event in PlayerControl class, and subscribe MainPage to the event.
  4. If the text is changed as a side effect of some application-wide event that affects more objects than just page and control — you could use a messenger.

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