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 を追加する

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

コード ビハインド ファイルのコンストラクターに次のように記述します。

this.DataContext = this.MyTodoList;

次に、ListBox を変更します。

<ListBox Width="400" Margin="10" ItemsSource="{Binding}">
于 2012-04-25T08:52:52.163 に答える
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 に答える
0

この上にデータコンテキストを定義する必要があります

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

于 2012-04-25T08:05:58.160 に答える