0

在 mvvm 应用程序中,窗口内的某些区域(实际上是 MainWindow 内的 UserControl)根据用户选择动态显示。

变化的块在 Stackpanels 内,我有 4 个,一次只显示一个。这是通过将Visibility绑定到 bool 属性并使用BooleanToVisibilityConverter 完成的。

我将所有备用 StackPanel 放在父控件中。它工作正常,但在 Visual Studio 的设计阶段我看到了所有这些,所以我在确定最终布局时遇到了问题。

如何轻松创建具有更多控件的布局,这些控件共享相同的窗口区域并一次显示一个?

4

2 回答 2

1

,但在 Visual Studio 的设计阶段,我看到了所有这些,所以我在确定最终布局时遇到了问题。

Document Outline通过在 Visual Studio 中调出选项卡可以轻松解决此问题。打开后,导航到可见树并切换眼球以明显隐藏/取消隐藏不感兴趣的控件;仅在设计期间

在此处输入图像描述

于 2021-06-21T14:27:20.183 回答
1

设置仅设计时数据上下文

通过设置设计时数据上下文可以大大简化在 Studio Designer 中开发 XAML。

一种实现是基于设置一个副本,该副本DataContext将在最终编译期间被忽略。

要实现切换,请向ViewModel添加一个属性,该属性将通知设计人员它是否可以在开发模式下使用。


我在这个例子中使用了 MVVMLight 情况,但是对于这个声明的实例属性IsInDesignMode和静态属性ViewModelBase.IsInDesignModeStatic

例子:

using System.ComponentModel;

namespace DataContextDesignTime.Example
{
    public class MyViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private bool _flag;
        public bool Flag
        {
            get => _flag;
            set
            {
                if (!Equals(_flag, value))
                {
                    _flag = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Flag)));
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(NotFlag)));
                }
            }
        }

        public bool NotFlag => !Flag;
    }
}
<Window x:Class="DataContextDesignTime.Example.ExamleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DataContextDesignTime.Example"
        mc:Ignorable="d"
        Title="ExamleWindow" Height="450" Width="800">
    <d:Window.DataContext>
        <local:MyViewModel Flag="True" NotFlag="True"/>
    </d:Window.DataContext>
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
    </Window.Resources>
    <StackPanel>
        <Border Background="LightBlue" Height="200"
                Visibility="{Binding Flag, Converter={StaticResource BooleanToVisibilityConverter}}"/>
        <Border Background="LightGreen" Height="400"
                Visibility="{Binding NotFlag, Converter={StaticResource BooleanToVisibilityConverter}}"/>
    </StackPanel>
</Window>

在此示例中,您可以在 XAML 或属性浏览器中更改属性值。
您将立即看到绑定、触发器的工作情况,以及某些数据的显示如何变化。


在此处输入图像描述


笔记

这在更复杂的虚拟机/包上可能会失败,但通常通过在设计时设置 DataContext 并不困难。

我需要重新编译项目以查看属性的更改。

XAML 设计器面板有一个«启用/禁用项目代码»按钮。 在此处输入图像描述

于 2021-06-23T05:16:19.880 回答