XAML:如何仅在设计模式下更改背景颜色?

Hou*_*man 7 silverlight xaml designer visual-studio

我有一个白色文本前景色和透明背景色的控件.稍后,此usercontrol将添加到带有真实背景颜色的不同控件中.

然而在设计这个时,在VS 2010中控制白色背景上的白色前景,我显然无法看到任何东西.无论如何,只为设计时间定义不同的颜色?

我试过这个:

if (System.ComponentModel.DesignerProperties.IsInDesignTool)
{
    LayoutRoot.Background = new SolidColorBrush(Colors.Blue);
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.有小费吗?

更新:

我不明白这对你们有什么用.我创建了一个新的Silverlight 4.0应用程序,并将这行代码插入到ctor中:

public MainPage()
        {
            InitializeComponent();
            LayoutRoot.Background = new SolidColorBrush(Colors.Blue);

        }

<UserControl x:Class="SilverlightApplication3.MainPage"
    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"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot">

    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

当我进入Designer时,我仍然不认为它是蓝色的.我甚至没有任何isInDesignTime条件.我在这里缺少什么?

谢谢,Kave

Wir*_*rie 3

这是一种方法:

if (System.ComponentModel.DesignerProperties.IsInDesignTool)
{
    LayoutRoot.Background = new SolidColorBrush(Colors.Yellow);
}
Run Code Online (Sandbox Code Playgroud)

如果您切换到创建模板化控件,则需要等待在 OnApplyTemplate 中进行设置,如下例所示:

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    Border b = this.GetTemplateChild("backBorder") as Border;
    if (b != null && System.ComponentModel.DesignerProperties.IsInDesignTool)
    {
        b.Background = new SolidColorBrush(Colors.Orange);
    }
}
Run Code Online (Sandbox Code Playgroud)

假设这是模板:

<Style TargetType="local:TemplatedControl1">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:TemplatedControl1">
                <Border x:Name="backBorder"
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)

我还喜欢在这样的代码周围添加条件编译指令,因为它仅适用于开发人员/设计人员,并且在运行时永远不需要。

#if DEBUG
if (System.ComponentModel.DesignerProperties.IsInDesignTool)
{
    LayoutRoot.Background = new SolidColorBrush(Colors.Yellow);
}
#endif
Run Code Online (Sandbox Code Playgroud)

请注意,只有当您正在创建的内容在设计时在另一个UserControl用户控件/控件中使用时,整个技术才有效。因此,如果我上面建议的代码放置在命名中,那么您必须有另一个包含控件实例的 ,才能在设计时查看行为。当您编辑当前编辑的控件时,其隐藏代码不会执行。它仅在包含在另一个主机中时才执行(例如在 Silverlight 中,另一个主机)。UserControlUserControlWithDesignModeUserControlUserControlHostUserControlWithDesignModeUserControl