Skip to content

Instantly share code, notes, and snippets.

@sakapon
Last active July 17, 2016 13:11
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/62e6227aaac8045217994b60f3c6dd9b to your computer and use it in GitHub Desktop.
Save sakapon/62e6227aaac8045217994b60f3c6dd9b to your computer and use it in GitHub Desktop.
BindingSample / BindingConsole / Indexer
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Data;
namespace BindingConsole
{
public class PersonMap : INotifyPropertyChanged
{
Dictionary<int, string> People = new Dictionary<int, string>();
public string this[int id]
{
get { return People[id]; }
set
{
if (People.ContainsKey(id) && People[id] == value) return;
People[id] = value;
NotifyPropertyChanged(Binding.IndexerName);
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName]string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
using System;
using System.Windows.Controls;
using System.Windows.Data;
namespace BindingConsole
{
class Program
{
[STAThread]
static void Main(string[] args)
{
// Binding Source with indexer.
var map = new PersonMap { [123] = "Taro" };
// Binding Target must be FrameworkElement.
var textBox = new TextBox { Text = "Default" };
Console.WriteLine(textBox.Text); // Default
// Binds target to source.
var binding = new Binding("[123]") { Source = map, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
textBox.SetBinding(TextBox.TextProperty, binding);
Console.WriteLine(textBox.Text); // Taro
// Changes source value.
map[123] = "Jiro";
Console.WriteLine(textBox.Text); // Jiro
// Changes target value.
textBox.Text = "Saburo";
Console.WriteLine(map[123]); // Saburo
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment