Skip to content

Instantly share code, notes, and snippets.

@sakapon
Last active July 3, 2016 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakapon/037ec63965b9e027802d502f3c6e8466 to your computer and use it in GitHub Desktop.
Save sakapon/037ec63965b9e027802d502f3c6e8466 to your computer and use it in GitHub Desktop.
BindingSample / BindingConsole / Collection
using System;
using System.Collections.ObjectModel;
using System.Windows.Controls;
namespace BindingConsole
{
class Program
{
[STAThread]
static void Main(string[] args)
{
var taro = new Person1 { Id = 123, Name = "Taro" };
var jiro = new Person1 { Id = 234, Name = "Jiro" };
// Binding Source (collection).
var people = new ObservableCollection<Person1> { taro };
// Binding Target.
var itemsControl = new ItemsControl();
Console.WriteLine(itemsControl.Items.Count); // 0
// MEMO: Binding Source のオブジェクト自体が変更されないのであれば、
// ItemsSource プロパティのデータ バインディングは必須ではありません。
// したがって、ここでは ItemsSource プロパティに直接代入しています。
itemsControl.ItemsSource = people;
Console.WriteLine(itemsControl.Items.Count); // 1
// Changes source collection.
people.Add(jiro);
Console.WriteLine(itemsControl.Items.Count); // 2
people.RemoveAt(0);
Console.WriteLine(itemsControl.Items.Count); // 1
// MEMO: ItemsSource に値を設定している場合、Items を直接変更しようとすると例外が発生します。
//itemsControl.Items.Add(jiro);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment