设置仅设计时数据上下文
通过设置设计时数据上下文可以大大简化在 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 设计器面板有一个«启用/禁用项目代码»按钮。
