source manage ItemsControl element in WPF C#

<Window x:Class="RetrieveOjbectFromBoundItemsControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:RetrieveOjbectFromBoundItemsControl"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:Person}">
            <Button Content="{Binding Name}" Tag="{Binding}" Click="Button_Click"/>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ItemsControl ItemsSource="{Binding}"/>
    </StackPanel>
</Window>

Code:

using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
namespace RetrieveOjbectFromBoundItemsControl
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new List<Person>
            {
                new Person{Name = "Tom"},
                new Person{Name = "Ken"},
                new Person{Name = "Jen"},
            };
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Person person = ((Button)sender).Tag as Person;
            Trace.WriteLine(person.Name);
        }
    }
    public class Person
    {
        public string Name { set; get; }
    }
}

Hope it helps.
William

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: