在XAML中为DataTemplate设计时间数据 [英] Design time data for datatemplate in xaml

查看:67
本文介绍了在XAML中为DataTemplate设计时间数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但是是否可以将一些示例数据定义为DataContext以便在DesignView中查看我的DataTemplate?

This may be a stupid question, but is it possible to define some sample data as DataContext in order to see my DataTemplate in DesignView?

此刻,我总是必须运行我的应用程序以查看我的更改是否有效。

At the moment I always have to run my application to see whether my changes are working.

例如包含以下代码的DesignView只会显示一个空的列表框:

E.g. with the following code DesignView just shows an empty list box:

 <ListBox x:Name="standardLayoutListBox" ItemsSource="{Binding myListboxItems}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Label Grid.Column="0" Content="{Binding text1}" />
                <Label Grid.Column="1" Content="{Binding text2}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


推荐答案

public class MyMockClass
{
    public MyMockClass()
    {
        MyListBoxItems.Add(new MyDataClass() { text1 = "test text 1", text2 = "test text 2" });
        MyListBoxItems.Add(new MyDataClass() { text1 = "test text 3", text2 = "test text 4" });
    }
    public ObservableCollection<MyDataClass> MyListBoxItems { get; set; }
}

public class MyDataClass
{
    public string text1 { get; set; }
    public string text2 { get; set; }
}

在您的XAML中

添加名称空间声明

 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

将模拟数据上下文添加到窗口/控件资源中

Add the mock data context to window/control resources

<UserControl.Resources> 
    <local:MyMockClass x:Key="DesignViewModel"/> 
</UserControl.Resources>

然后修改您的列表框以引用设计时间对象

Then Modify Your ListBox to Reference the design time object

<ListBox x:Name="standardLayoutListBox" 
 d:DataContext="{Binding Source={StaticResource DesignViewModel}}"
ItemsSource="{Binding MyListBoxItems}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Label Grid.Column="0" Content="{Binding text1}" />
                <Label Grid.Column="1" Content="{Binding text2}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这篇关于在XAML中为DataTemplate设计时间数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆