1
我想在WPF GridView
的設計窗口中顯示的虛擬數據,發現了一個類似的例子:Answer: Design time data for datatemplate in xaml - Stack Overflow錯誤實行設計時間數據模板
我創建了一個新的WPF應用程序(.NET框架4.6.1)命名WpfDataTemplate
並將該示例的代碼片段複製到MainWindow.xaml.cs
和MainWindow.xaml
中。所有新增內容均在##
的評論中註明。
意外行爲:
線
<local:MyMockClass x:Key="DesignViewModel" />
產生錯誤「不設置到對象的實例對象引用」。test text #
字符串不會顯示在設計器中。test text #
字符串在運行時不顯示在窗口中。
問題:
什麼是錯誤的原因是什麼?
我需要更改代碼才能按預期工作?
MainWindow.xaml
<Window x:Class="WpfDataTemplate.MainWindow"
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"
xmlns:local="clr-namespace:WpfDataTemplate"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<!-- ## BEGIN ADD -->
<Window.Resources>
<local:MyMockClass x:Key="DesignViewModel" />
</Window.Resources>
<!-- ## END ADD -->
<Grid>
<!-- ## BEGIN ADD -->
<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>
<!-- ## END ADD -->
</Grid>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// ## BEGIN ADD
using System.Collections.ObjectModel;
// ## END ADD
namespace WpfDataTemplate
{
// ## BEGIN ADD
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; }
}
// ## END ADD
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}