1

我想了解来自 msdn 的示例(http://msdn.microsoft.com/en-us/library/ms742521.aspx#defining_simple_datatemplate)。

XAML 代码:

<ListBox Width="400" Margin="10" ItemsSource="{Binding Source={StaticResource MyTodoList}}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=TaskName}" />
         <TextBlock Text="{Binding Path=Description}"/>
         <TextBlock Text="{Binding Path=Priority}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

文本块中的数据是对象的属性,对吗?对象在代码隐藏文件中的列表(?)myTodoList 中?

protected ObservableCollection<TODO> _myTodoList= new ObservableCollection<TODO>();
public ObservableCollection<TODO> MyTodoList
{
    get { return _myTodoList; }
}

添加待办事项

TODO t1 = new TODO();
t1.TaskName = "TaskName1";
t1.Description = "Description1";
t1.Priority = "Priority1";
_myTodoList.Add(t1);

TODO t2 = new TODO();
t2.TaskName = "TaskName2";
t2.Description = "Description2";
t2.Priority = "Priority2";
_myTodoList.Add(t2);

我的测试 TODO 类:

public class TODO
{
    public string TaskName { get; set; }
    public string Description { get; set; }
    public string Priority { get; set; }
}

但是代码抛出异常...... 在此处输入图像描述

怎么了?

4

3 回答 3

2

您必须声明 StaticResource:

<Window ...
        xmlns:local="clr-namespace:SDKSample"
        ...
        >
    <Window.Resources>
        <local:Tasks x:Key="MyTodoList"/>
    </Window.Resources>

来自 SDKSample:

public class Tasks : ObservableCollection<Task>
{
    public Tasks(): base()
    {
        Add(new Task("Groceries", "Pick up Groceries and Detergent", 2, TaskType.Home));
        Add(new Task("Laundry", "Do my Laundry", 2, TaskType.Home));
        Add(new Task("Email", "Email clients", 1, TaskType.Work));
        Add(new Task("Clean", "Clean my office", 3, TaskType.Work));
        Add(new Task("Dinner", "Get ready for family reunion", 1, TaskType.Home));
        Add(new Task("Proposals", "Review new budget proposals", 2, TaskType.Work));
    }
}
于 2012-04-25T08:08:07.317 回答
2

在您的代码隐藏文件中,在构造函数中输入以下内容:

this.DataContext = this.MyTodoList;

然后更改您的列表框:

<ListBox Width="400" Margin="10" ItemsSource="{Binding}">
于 2012-04-25T08:52:52.163 回答
0

您确实在此顶部定义了数据上下文

<ObjectDataProvider ObjectType="{x:Type m:yourvmtype}" x:Key="MyTodoList" MethodName="GetStrings"/> </StackPanel.Resources>

于 2012-04-25T08:05:58.160 回答