I'm a beginner in WP8.
I have a problem...
For Example:
I have 2 pages in my windows phone application, and on first page I have 3 buttons and on second page I have a TextBlock control.
How can I change its text property on the second page by clicking the buttons which are on the first page?
I only know how to change text when the controls are on the same page:
private void button1_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text= "Hello!";
}
This seems to me like bad practice, but it can be done by getting and storing instance of the page with the textblock in a global variable and accessing the textblock from that instance.eg
public Page myFirstPage = null;
public partial class FirstPage : Page
{
FirstPage()
{
initializeComponent();
}
void onLoadedEvent(Object Sender, Eventargs e)
{
myFirstPage = this;
}
}
Then you can access every thing in any other page by doing this
myFirstPage.TextBlock1 = "FooBar";
You can address this problem in MVVM way. Have a proper viewmodel to store your data :
public class MyViewModel
{
public String WelcomeText { get; set; }
}
Declare property of type above viewmodel in App.xaml.cs
, so that you can share same data across application pages :
public MyViewModel MyViewModel = new MyViewModel();
Set DataContext
of both pages to the same viewmodel :
public Page1()
{
InitializeComponents();
this.DataContext = App.MyViewModel;
}
public Page2()
{
InitializeComponents();
this.DataContext = App.MyViewModel;
}
Data-bind textblock in page 2 :
<TextBlock Text="{Binding WelcomeText}"/>
Then in button click event handler of page 1, simply update the viewmodel property :
private void button1_Click(object sender, RoutedEventArgs e)
{
App.MyViewModel.WelcomeText= "Hello!";
}
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.