첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ 객체 동적 바인딩 처리하기

----------------------------------------------------------------------------------------------------

 

MainWindow.xaml

 

 

<Window

    x:Class="TestProject.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="clr-namspace:TestProject"

    Width="600"

    Height="450"

    Title="객체 동적 바인딩 처리하기">

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="*"    />

            <RowDefinition Height="Auto" />

        </Grid.RowDefinitions>

        <Border

            Margin="5"

            BorderThickness="1"

            BorderBrush="Black">

            <ListBox Name="listBox" Grid.Row="0" />

        </Border>

        <StackPanel Grid.Row="1" Orientation="Horizontal">

            <Button Name="schoolButton"      Margin="5" Width="85" Content="School"       />

            <Button Name="studentButton"     Margin="5" Width="85" Content="Student"      />

            <Button Name="currentItemButton" Margin="5" Width="85" Content="Current Item" />

        </StackPanel>

    </Grid>

</Window>

 

 

MainWindow.xaml.cs

 

 

using System;

using System.ComponentModel;

using System.Collections.ObjectModel;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

 

namespace TestProject

{

    /// <summary>

    /// 메인 윈도우

    /// </summary>

    public partial class MainWindow : Window

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 속성 설명자 컬렉션

        /// </summary>

        private PropertyDescriptorCollection propertyDescriptorCollection = null;

 

        /// <summary>

        /// 체크 여부 속성 설명자

        /// </summary>

        private PropertyDescriptor isCheckedPropertyDescriptor = null;

 

        /// <summary>

        /// 텍스트 속성 설명자

        /// </summary>

        private PropertyDescriptor textPropertyDescriptor = null;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainWindow()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainWindow()

        {

            InitializeComponent();

 

            this.schoolButton.Click      += schoolButton_Click;

            this.studentButton.Click     += studentButton_Click;

            this.currentItemButton.Click += currentItemButton_Click;

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        //////////////////////////////////////////////////////////////////////////////// Event

 

        #region School 버튼 클릭시 처리하기 - schoolButton_Click(sender, e)

 

        /// <summary>

        /// School 버튼 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void schoolButton_Click(object sender, RoutedEventArgs e)

        {

            ObservableCollection<School> collection = School.GetCollection();

 

            this.listBox.ItemsSource = collection;

 

            this.propertyDescriptorCollection = TypeDescriptor.GetProperties(collection[0]);

            this.isCheckedPropertyDescriptor  = this.propertyDescriptorCollection["IsChecked"];

            this.textPropertyDescriptor       = this.propertyDescriptorCollection["SchoolName"];

 

            this.listBox.ItemTemplate = GetDataTemplate(typeof(School), "IsChecked", "SchoolName");

        }

 

        #endregion

 

        #region Student 버튼 클릭시 처리하기 - studentButton_Click(sender, e)

 

        /// <summary>

        /// Student 버튼 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void studentButton_Click(object sender, RoutedEventArgs e)

        {

            ObservableCollection<Student> collection = Student.GetCollection();

 

            this.listBox.ItemsSource = collection;

 

            this.propertyDescriptorCollection = TypeDescriptor.GetProperties(collection[0]);

            this.isCheckedPropertyDescriptor  = this.propertyDescriptorCollection["IsChecked"];

            this.textPropertyDescriptor       = this.propertyDescriptorCollection["StudentName"];

 

            this.listBox.ItemTemplate = GetDataTemplate(typeof(School), "IsChecked", "StudentName");

        }

 

        #endregion

 

        #region Current Item 버튼 클릭시 처리하기 - currentItemButton_Click(sender, e)

 

        /// <summary>

        /// Current Item 버튼 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void currentItemButton_Click(object sender, RoutedEventArgs e)

        {

            object item = this.listBox.SelectedItem;

 

            if(item != null)

            {

                bool   isChecked = (bool)this.isCheckedPropertyDescriptor.GetValue(item);

                string text      = (string)this.textPropertyDescriptor.GetValue(item);

 

                MessageBox.Show(string.Format("{0}, {1}", isChecked, text));

            }

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////// Function

 

        #region 데이터 템플리트 구하기 - GetDataTemplate(itemType, isCheckedPropertyName, textPropertyName)

 

        /// <summary>

        /// 데이터 템플리트 구하기

        /// </summary>

        /// <param name="itemType">항목 타입</param>

        /// <param name="isCheckedPropertyName">체크 여부 속성명</param>

        /// <param name="textPropertyName">텍스트 속성명</param>

        /// <returns>데이터 템플리트</returns>

        private DataTemplate GetDataTemplate(Type itemType, string isCheckedPropertyName, string textPropertyName)

        {

            DataTemplate dataTemplate = new DataTemplate();

 

            dataTemplate.DataType = itemType;

 

            FrameworkElementFactory stackPanelFrameworkElementFactory = new FrameworkElementFactory(typeof(StackPanel));

 

            stackPanelFrameworkElementFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);

 

            FrameworkElementFactory checkBoxFrameworkElementFactory = new FrameworkElementFactory(typeof(CheckBox));

 

            checkBoxFrameworkElementFactory.SetValue(CheckBox.WidthProperty            , 20d                     );

            checkBoxFrameworkElementFactory.SetValue(CheckBox.VerticalAlignmentProperty, VerticalAlignment.Center);

 

            checkBoxFrameworkElementFactory.SetBinding(CheckBox.IsCheckedProperty, new Binding(isCheckedPropertyName));

 

            stackPanelFrameworkElementFactory.AppendChild(checkBoxFrameworkElementFactory);

 

            FrameworkElementFactory textBlockFrameworkElementFactory = new FrameworkElementFactory(typeof(TextBlock));

 

            textBlockFrameworkElementFactory.SetBinding(TextBlock.TextProperty, new Binding(textPropertyName));

 

            stackPanelFrameworkElementFactory.AppendChild(textBlockFrameworkElementFactory);

 

            dataTemplate.VisualTree = stackPanelFrameworkElementFactory;

 

            return dataTemplate;

        }

 

        #endregion

    }

}

 

 

School.cs

 

 

using System.Collections.ObjectModel;

 

namespace TestProject

{

    /// <summary>

    /// 학교

    /// </summary>

    public class School

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 체크 여부 - IsChecked

 

        /// <summary>

        /// 체크 여부

        /// </summary>

        public bool IsChecked { get; set; }

 

        #endregion

 

        #region 학교 ID - SchoolID

 

        /// <summary>

        /// 학교 ID

        /// </summary>

        public string SchoolID { get; set; }

 

        #endregion

 

        #region 학교명 - SchoolName

 

        /// <summary>

        /// 학교명

        /// </summary>

        public string SchoolName { get; set; }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 컬렉션 구하기 - GetCollection()

 

        /// <summary>

        /// 컬렉션 구하기

        /// </summary>

        /// <returns>컬렉션</returns>

        public static ObservableCollection<School> GetCollection()

        {

            ObservableCollection<School> collection = new ObservableCollection<School>();

 

            collection.Add(new School() { SchoolID = "0001", SchoolName = "학교1" });

            collection.Add(new School() { SchoolID = "0002", SchoolName = "학교2" });

            collection.Add(new School() { SchoolID = "0003", SchoolName = "학교3" });

 

            return collection;

        }

 

        #endregion

    }

}

 

 

Student.cs

 

 

using System.Collections.ObjectModel;

 

namespace TestProject

{

    /// <summary>

    /// 학생

    /// </summary>

    public class Student

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 체크 여부 - IsChecked

 

        /// <summary>

        /// 체크 여부

        /// </summary>

        public bool IsChecked { get; set; }

 

        #endregion

 

        #region 학생 ID - StudentID

 

        /// <summary>

        /// 학생 ID

        /// </summary>

        public string StudentID { get; set; }

 

        #endregion

 

        #region 학생명 - StudentName

 

        /// <summary>

        /// 학생명

        /// </summary>

        public string StudentName { get; set; }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 컬렉션 구하기 - GetCollection()

 

        /// <summary>

        /// 컬렉션 구하기

        /// </summary>

        /// <returns>컬렉션</returns>

        public static ObservableCollection<Student> GetCollection()

        {

            ObservableCollection<Student> collection = new ObservableCollection<Student>();

 

            collection.Add(new Student() { StudentID = "0001", StudentName = "학생1" });

            collection.Add(new Student() { StudentID = "0002", StudentName = "학생2" });

            collection.Add(new Student() { StudentID = "0003", StudentName = "학생3" });

 

            return collection;

        }

 

        #endregion

    }

}

 

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG

댓글을 달아 주세요