【问题标题】:WPF MVVM switch usercontrolsWPF MVVM 切换用户控件
【发布时间】:2013-10-22 04:20:03
【问题描述】:

我是 MVVM 和 WPF 的新手,但我知道 MVVM 中发生了什么。我在主窗口中的用户控件之间切换时遇到问题。在我的应用程序中,我有: 带有日志和 2 个链接的 MainWindow.xaml:全部显示并新建。当然我有它的 ViewModel。我还有 2 个 UserControls:ShowAll 和 Create with ViewModels 以及其中的所有逻辑(添加数据等)。单击链接时如何显示创建表单单击 ShowAll 创建新或显示全部?

在windowForms中我只是隐藏了UC,但是这里没有代码:)

我的 MainWindow.xaml:

<Window x:Class="Test.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Name}"/>
            <Button Content="Change" Command="{Binding ChangeCommand}"/>
        </StackPanel>
    </Grid>
</Window>

我的 MainWindowViewModel:

class MainWindowViewModel : BaseViewModel
{
    private Person _person;
    private BaseCommand _changeCommand;

    public MainWindowViewModel()
    {
        _person = new Person();
    }

    public string Name
    {
        get
        {
            return _person.Name;
        }
        set
        {
            if (_person.Name != value)
                _person.Name = value;
            OnPropertyChanged(() => Name);
        }
    }

    public ICommand ChangeCommand
    {
        get
        {
            if (_changeCommand == null)
                _changeCommand = new BaseCommand(() => change());
            return _changeCommand;
        }
    }

    private void change()
    {
        _person = new Person();
        Name = _person.Imie;
    }
}

在 Create 和 ShowAll 中没有代码。在 xaml 中只有一个标签,VM 是空的。只是为了测试。

感谢您的帮助!

【问题讨论】:

  • 发布相关代码和 XAML。 BTW MVVM 并不意味着没有代码。 MVVM 意味着不要将业务逻辑放在代码后面。

标签: c# wpf mvvm user-controls


【解决方案1】:

您可以使用ContentControl 根据绑定到ContentControl 的ViewModel 类型显示特定的DataTemplate

http://www.japf.fr/2009/03/thinking-with-mvvm-data-templates-contentcontrol/

绑定到 ShowAll 按钮的命令可以简单地更改绑定到内容控件的主 ViewModel 上的属性。

【讨论】:

  • 是的,听起来不错……他也可以为此使用一些框架或消息传递类。
  • 非常感谢!这很容易 :) 顺便说一句,这些数据模板很棒。您可以在不同的控件中使用一种类型。哇:)
猜你喜欢
  • 1970-01-01
  • 2011-06-28
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
  • 2020-06-28
  • 2016-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多