WPF / C# - ListBox示例是ItemsSource

时间:2012-04-25 07:56:34

标签: c# wpf listbox msdn

我想了解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>

文本块中的数据是来自对象的属性,这是对的吗? Object位于代码隐藏文件的列表(?)myTodoList中?

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

添加TODO的

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

但代码抛出异常...... enter image description here

怎么了?

3 个答案:

答案 0 :(得分: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));
    }
}

答案 1 :(得分:2)

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

this.DataContext = this.MyTodoList;

然后更改ListBox:

<ListBox Width="400" Margin="10" ItemsSource="{Binding}">

答案 2 :(得分:0)

您已在此

的顶部定义了datacontext

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