Galilo Galilo
Galilo Galilo

Reputation: 569

how to use the same instance of the view in the navigationservice.navigate() in wpf

I have two views (viewA and viewB), where I navigate between them in the mainwindow using navigationservice. I need to use the same instance of viewA after navigating multiple times.

Upvotes: 0

Views: 694

Answers (2)

yaho cho
yaho cho

Reputation: 1779

I am using an instance of Page for navigating pages. Each Page can have each viewmodel to hold data. And, You just need to bind data if you want to update data from viewmodel in real time.

MainWindow xaml

<StackPanel>
    <Button Click="Button_Click">Change Page</Button>
    <Frame Name="ContentPage"></Frame>
</StackPanel>

MainWindow Behind Code

    private Page viewA = new ViewA();
    private Page viewB = new ViewB();

    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }

    private int page;

    public void Button_Click(object sender, EventArgs e)
    {
        page++;
        if (page % 2 == 0)
            ContentPage.Navigate(viewA);
        else
            ContentPage.Navigate(viewB);
    }

ViewA xaml

<Grid>
    <TextBlock Name="ViewAText"/>
</Grid>

ViewA behind code

    public ViewA()
    {
        InitializeComponent();
        DataContext = new ViewAViewModel();
        ViewAViewModel viewmodel = DataContext as ViewAViewModel;
        ViewAText.Text = viewmodel.text;
    }

ViewB xaml

<Grid>
    <TextBlock Name="ViewBText"/>
</Grid>

ViewB behind code

    public ViewB()
    {
        InitializeComponent();
        DataContext = new ViewBViewModel();
        ViewBViewModel viewmodel = DataContext as ViewBViewModel;
        ViewBText.Text = viewmodel.text;
    }

Upvotes: 0

Andy
Andy

Reputation: 12276

I would make this generic.

You don't say what navigationservce is or what the views are.

Either, maintain your list of views yourself.

Add a dictionary with Key of Type and value Page ( or object or whatever a view is in your app ).

When you navigate you can then navigate to a Type and check if there's already an entry in your dictionary using .ContainsKey(theType). If there's one there then navigate to that by passing it into your navigation process. If there's not one there then

Activator.CreateInstance(theType)

To create a page/view/whatever.

Add this to your dictionary and navigate to it.

Or

Use a dependency injection container such as unity to .Resolve a singleton for each view.

Either way, you may need some new method or changes to an existing one depending on what your navigation service does.

Upvotes: 0

Related Questions