2011-10-13 40 views
12

的DataTemplate這可能是一個愚蠢的問題,但有可能定義爲了看我的DesignView DataTemplate中一些樣本數據的DataContext?設計時間數據在XAML

目前,我總是跑我的應用程序,看看我的變化是否有效。

E.g.用下面的代碼DesignView只是顯示一個空的列表框:

<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> 
+0

請參閱這篇文章提出的解決方案:http://stackoverflow.com/questions/1889966/what-approaches-are-available-to-dummy-設計時數據在WPF –

+0

現在我讀了很多樣本​​,但我真的不能在設計時填充這個簡單的Listbox。我確定我錯過了一些東西,但是我找不到什麼。你有可能爲我的列表框提供一個工作示例嗎? – MTR

+0

請參閱下面的示例代碼的答案。 –

回答

15
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" 

添加到窗口/控制資源的模擬數據上下文

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

然後修改您的列表框引用設計時對象

<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> 
+3

增加myListBoxItems =新的ObservableCollection ()後;要MyMockClass的構造沒有錯誤消息,但列表框仍然是空 – MTR

+0

我看不到任何其他的問題,如果你是。對於想要設計時間數據真的很認真,我會建議你看看MEF的概念。我使用[Cinch](http://www.codeproject.com/KB/WPF/CinchV2_3.aspx)(搜索「ViewModel Design」看到一些設計時支持)對不起,我不能用一個簡單的解決方案幫助 –

+1

不要忘記設置MC:。忽略的命名空間中的聲明: 的xmlns:MC =「http://schemas.openxmlformats.org/標記兼容性/ 2006「 mc:Ignorable =「d」 –