简体   繁体   中英

Dynamically Accessing MainPage controls in child UserControl's from codebehind in metro application?

i have a MainPage in which part of the screen i have empty grid named customview , in which i want to dynamically add and remove different views(different usercontrols). now i have attached one usercontrol(view1) to that empty grid(part of the MainPage) in this way :- customview is the empty grid , view1 is the usercontrol which i have designed,and on navigated to MainPage i am doing this :-

protected override void OnNavigatedTo(NavigationEventArgs e)
{
customview.Children.Clear();
View1 firstview = new View1 ();
customview.Children.Add(firstview); 
}

Now , View1 (usercontrol) is having a button1 , on that button1 click i have to remove view1 and add view2 (another user control) to the same grid named customview present in MainPage.

which i have tried it in this way but no luck :-

private void button1_Click_1(object sender, RoutedEventArgs e)
{
MainPage main = new MainPage();
View2 secview = new View2 ();
Grid grd = main.FindName("customview") as Grid;
grd .Children.Clear();
grd .Children.Add(secview);
}

Please let me know where am i doing wrong ? Thanks in advance.

Label lbl = (Label)this.Page.FindControl("controlID");
string labelText = lbl.Text;

Consider the using of ContentControl instead of doing this way. Using that you'll be able to change its Content, adding wherever you want.

add this to your view :

            <ContentControl Name="region1ContentControl" 
                        Grid.Row="1"
                        Grid.Column="1"
                        Margin="0,10"                           
                        Style="{StaticResource ContentControlStyle}" />

so on code behind you'll be able to do like this:

region1ContentControl.Content = AnyObject(including views)

This will be easier to work than changing views all the time.

Hope it helps

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