Last active
July 17, 2016 13:11
-
-
Save sakapon/62e6227aaac8045217994b60f3c6dd9b to your computer and use it in GitHub Desktop.
BindingSample / BindingConsole / Indexer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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