简体   繁体   English

如何在 WPF 中使用 MVVM 调用仅创建一个实例的用户控件?

[英]How to call User Control creating just one instance using MVVM in WPF?

I'm working in a WPF project and a newer on this, I'm using the MVVM patter in my project.我在一个 WPF 项目和一个更新的项目中工作,我在我的项目中使用 MVVM 模式。

I have a MainWindows which calls User Controls and I have a MainWindowsModel which helps me to Create an instance, save them in a variable for opening in my MainWindows...我有一个调用用户控件的 MainWindows,我有一个 MainWindowsModel,它可以帮助我创建一个实例,将它们保存在一个变量中以便在我的 MainWindows 中打开...

My problems comes here, when I use the menu of my window (look the photos below) the User Control is refresing like creating a new instance...我的问题来了,当我使用我的 window 的菜单(看下面的照片)时,用户控件正在刷新,就像创建一个新实例一样......

I create a repository where i simulate my problem, try to write in the textBox and then click on other bottom Menu, Then return to the before Button you won't be able to watch the message you wrote there.我创建了一个存储库,在那里我模拟了我的问题,尝试在文本框中写入,然后单击其他底部菜单,然后返回到之前的按钮,你将无法看到你在那里写的消息。

Hope some helps me with this because i have no idea how to manage User Control just creating one Instance and don't save data when i change between UserControls.希望有人能帮助我解决这个问题,因为我不知道如何只创建一个实例来管理用户控件,并且在用户控件之间切换时不保存数据。

Look at the image if I didn't explain well如果我没有解释好,请看图片在此处输入图像描述

The repo for this question with interface in the photo: Click on here to open the Repo这个问题的回购协议在照片中的界面:点击这里打开回购协议

I was looking for examples on other post but i didn't fine a way to make my information stays on my UserControl.我正在寻找其他帖子上的示例,但我没有很好的方法让我的信息保留在我的 UserControl 上。 I will be active for this question...我会积极回答这个问题...

The information is not supposed to "stay in the UserControl .该信息不应“留在UserControl中。

You should bind the TextBox to a property of the view model and store the string value there.您应该将TextBox绑定到视图 model 的属性并将string值存储在那里。 It won't/shouldn't be stored in the view that gets unloaded.它不会/不应该存储在被卸载的视图中。

HomeView.xaml :主页视图.xaml

<TextBox Text="{Binding Text}"
                FontSize="20"
                Margin="10,10,0,0"
                Foreground="Green"
                Width="300"
                Height="50"/>

HomeViewModel:主页视图模型:

public class HomeViewModel : ViewModelBase
{
    private string _text = "Write something";
    public string Text
    {
        get { return _text; }
        set { _text = value; OnPropertyChanged(nameof(Text)); }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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