2012年9月4日火曜日

INotifyPropertyChanged サンプル

INotifyPropertyChanged インターフェイスを実装するサンプルです。
ボタンクリックのタイミングでデータを書き換えます。変更通知により UI 側にも変更内容が反映されます。


<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Height="23" HorizontalAlignment="Left"
                 Margin="18,29,0,0" Name="textBox1"
                 VerticalAlignment="Top" Width="207"
                 Text="{Binding Path=ProductName}"
                 />
        <Button Content="Click to change data!"
                Height="23"
                HorizontalAlignment="Left"
                Margin="18,93,0,0" Name="button1"
                VerticalAlignment="Top"
                Width="207" Click="button1_Click"
                />
    </Grid>
</Window>

public partial class MainWindow : Window
{
    Product p;

    public MainWindow()
    {
        InitializeComponent();

        // Create Banana
        p = new Product("Banana");
        this.DataContext = p;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        var p2 = this.DataContext as Product;

        // Change product to Orange
        p2.ProductName = "Orange";
    }
}

public class Product : INotifyPropertyChanged
{
    private string name;

    public event PropertyChangedEventHandler PropertyChanged;

    public Product(string value)
    {
        this.name = value;
    }

    public string ProductName
    {
        get { return name; }
        set
        {
            name = value;

            OnPropertyChanged("ProductName");
        }
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}