Design time data for datatemplate in xaml

北城以北 提交于 2020-01-02 00:59:07

问题


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.

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>

回答1:


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; }
}

In Your XAML

Add the namespace declaration

 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>


来源:https://stackoverflow.com/questions/7753843/design-time-data-for-datatemplate-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!