在使用控件本身时,如何使用假数据设计时初始化XAML UserControl?

Nil*_*zor 2 xaml visual-studio windows-8 winrt-xaml

我有一个基本的WinRT XAML UserControl,它有一个依赖属性,如下所示.用户控件显然只在另一个Page或UserControl中使用时才构造设计时.当我使用用户控件本身在设计器中工作时,不会呈现文本"Hello world".在这种情况下,如何让设计器使用数据初始化用户控件?

XAML:

<UserControl
    x:Class="GTWin8.Ui.SimpleBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:GTWin8.Ui"
    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"
    x:Name="ThisControl">

    <Grid Background="Black">
        <TextBlock Text="{Binding Path=Message, ElementName=ThisControl}" 
                   HorizontalAlignment="Left" Margin="10,10,0,0" 
                   TextWrapping="Wrap" VerticalAlignment="Top" Height="280" Width="380"/>
    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

代码隐藏:

public sealed partial class SimpleBinding : UserControl
{
    public static DependencyProperty MessageProperty = DependencyProperty.Register(
           "Message", typeof(String), typeof(SimpleBinding), new PropertyMetadata(null));

    public String Message
    {
        get { return (String)GetValue(MessageProperty); }
        set { SetValue(MessageProperty, value); }
    }

    public SimpleBinding()
    {
        this.InitializeComponent();
        Message = "Hello world";
    }
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*xon 5

嗯,一个更简单的方法是声明性调用.

<UserControl>

    <d:Page.DataContext>
        <sample:FakeViewModel />
    </d:Page.DataContext>

    <Grid>
        <!-- your bind/content -->
    </Grid>

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

我在所有项目中都使用它,因为它可以提供设计时数据,而不会影响我的运行时体验.更多:http://blog.jerrynixon.com/2012/06/windows-8-15-more-reasons-why-i-choose.html