【问题标题】:how to set visibility of MainWindow controls like stackpanel from another .xaml page如何从另一个 .xaml 页面设置 MainWindow 控件(如 stackpanel)的可见性
【发布时间】:2012-09-10 07:23:57
【问题描述】:

我正在以 MVVM 模式创建一个示例 WPF 应用程序来实现母版页内容页面的概念。 在我的 wpf 应用程序中,我有一个 MainWindow 页面和 3 个用户控件,例如 Page1、Page2 和 Page3。

MainWindow.xaml 包含一个网格、一个堆栈面板和一个框架。

MainWindow.xaml 中的网格包含一个图像控件,堆栈面板包含一个 TextBlock 和 3 个按钮。

这个框架首先按页面填充或加载如下:

        // Load and show the MainWindow

        MainWindowViewModel vm = new MainWindowViewModel();
        MainWindow main = new MainWindow();
        Navigator.NavigationService = main.NavigationFrame.NavigationService;
        main.DataContext = vm;
        main.Show();

        // Load and navigate to the first page
        Page1ViewModel pagevm = new Page1ViewModel();
        Page1 p1 = new Page1();
        p1.DataContext = pagevm;
        Navigator.NavigationService.Navigate(p1);

通过使用它,我可以从 page1 导航到 page2,然后从 page2 导航到 page3。

这里我的问题最初是堆栈面板应该在显示 page1 和 page2 时禁用。 但是在从 page2 导航到 page3 时,这意味着每当我显示 page3 时,应该启用 MainWindow 中的堆栈面板,并且按钮只能在 page3 中执行其点击事件。

请告诉我这个问题的解决方案。

【问题讨论】:

    标签: wpf mvvm


    【解决方案1】:

    你可以将当前页面提取到MainWindowViewModel并添加一个返回的属性,不管StackPanel是否启用:

    MainWindowViewModel:
    private Page _currentPage = null;
    public Page CurrentPage
    {
        get { return _currentPage; }
        set
        {
            _currentPage = value;
            Notify("CurrentPage");
            Notify("StackPanelEnabled");          
        }
    }
    
    public bool StackPanelEnabled
    {
        get { return CurrentPage is Page3; }
    }
    

    Notify 是引发PropertyChanged 事件的辅助方法。将FrameContent属性绑定到CurrentPage

    <Frame Content="{Binding CurrentPage}"/>
    

    使用它:

    Page1ViewModel pagevm = new Page1ViewModel();
    Page1 p1 = new Page1();
    p1.DataContext = pagevm;
    vm.CurrentPage = p1;
    

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 2014-01-24
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多