禁用VS Designer的DataContext

时间:2011-08-29 09:19:40

标签: wpf xaml

我想在WPF设计器中禁用DataContext实例的创建(在VS中不混合)。 到目前为止我所做的是以下代码:

<Window ....
d:DataContext="{d:DesignInstance local:Class1, IsDesignTimeCreatable=True}">
    <Window.DataContext>
        <local:Class2 d:IsDesignTimeCreatable="False/>
    </Window.DataContext>
</Window>

虽然在设计时使用了Class1中的数据,但仍在创建Class2的实例。

我知道我可以使用一些代码来检查我是否在设计时,但我想通过XAML解决这个问题!

任何建议?

1 个答案:

答案 0 :(得分:1)

您可以查看附加的属性DesignerProperties.IsInDesignMode。这里有一些建议,但没有一个看起来很干净,最后,我认为在代码中使用几行是最简单的解决方案。

  • 如果DataContext对象在Style中设置(但在将来的VS Designer升级中可能会改变),我认为DataContext对象不会被实例化。
  • 您可以使用转换器将IsInDesignMode绑定到Class2,该转换器返回IsInDesignMode的实例或null,具体取决于DataTrigger
  • 的值
  • 使用<Window ... xmlns:pf="clr-namespace:System.ComponentModel;assembly=PresentationFramework"> <Window.Style> <Style TargetType="Window"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=(pf:DesignerProperties.IsInDesignMode)}" Value="False"> <Setter Property="DataContext"> <Setter.Value> <local:Class2 /> </Setter.Value> </Setter> </DataTrigger> </Style.Triggers> </Style> </Window.Style> <!--...--> </Window> 。只有Xaml,但代码很多..

实施例

{{1}}