첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

TestProject.zip
0.04MB

▶ LinqExtension.cs

using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace TestProject
{
    /// <summary>
    /// LINQ 확장
    /// </summary>
    public static class LinqExtensions
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public

        #region 관측 가능 컬렉션 구하기 - ToObservableCollection<TItem>(sourceEnumerable)

        /// <summary>
        /// 관측 가능 컬렉션 구하기
        /// </summary>
        /// <typeparam name="TItem">항목 타입</typeparam>
        /// <param name="sourceEnumerable">소스 열거 가능 목록</param>
        /// <returns>관착 가능 컬렉션</returns>
        public static ObservableCollection<TItem> ToObservableCollection<TItem>(this IEnumerable<TItem> sourceEnumerable)
        {
            ObservableCollection<TItem> collection = new ObservableCollection<TItem>();

            foreach(TItem item in sourceEnumerable)
            {
                collection.Add(item);
            }

            return collection;
        }

        #endregion
    }
}

 

728x90

 

▶ ListBoxSelectionBehavior.cs

using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace TestProject
{
    /// <summary>
    /// 리스트 박스 선택 동작
    /// </summary>
    public class ListBoxSelectionBehavior : Behavior<ListBox>
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public

        #region 선택 항목 리스트 속성 - SelectedItemsProperty

        /// <summary>
        /// 선택 항목 리스트 속성
        /// </summary>
        public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register
        (
            nameof(SelectedItems),
            typeof(IList),
            typeof(ListBoxSelectionBehavior),
            new FrameworkPropertyMetadata
            (
                null,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                SelectedItemsPropertyChangedCallback
            )
        );

        #endregion
        #region 선택 값 리스트 속성 - SelectedValuesProperty

        /// <summary>
        /// 선택 값 리스트 속성
        /// </summary>
        public static readonly DependencyProperty SelectedValuesProperty = DependencyProperty.Register
        (
            nameof(SelectedValues),
            typeof(IList),
            typeof(ListBoxSelectionBehavior),
            new FrameworkPropertyMetadata
            (
                null,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                SelectedValuesPropertyChangedCallback
            )
        );

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////// Instance
        //////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 뷰 처리 여부
        /// </summary>
        private bool viewHandled;

        /// <summary>
        /// 모델 처리 여부
        /// </summary>
        private bool modelHandled;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 선택 항목 리스트 - SelectedItems

        /// <summary>
        /// 선택 항목 리스트
        /// </summary>
        public IList SelectedItems
        {
            get => (IList)GetValue(SelectedItemsProperty);
            set => SetValue(SelectedItemsProperty, value);
        }

        #endregion
        #region 선택 값 리스트 - SelectedValues

        /// <summary>
        /// 선택 값 리스트
        /// </summary>
        public IList SelectedValues
        {
            get => (IList)GetValue(SelectedValuesProperty);
            set => SetValue(SelectedValuesProperty, value);
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region 선택 항목 리스트 속성 변경시 콜백 처리하기 - SelectedItemsPropertyChangedCallback(d, e)

        /// <summary>
        /// 선택 항목 리스트 속성 변경시 콜백 처리하기
        /// </summary>
        /// <param name="d">의존 객체</param>
        /// <param name="e">이벤트 인자</param>
        private static void SelectedItemsPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ListBoxSelectionBehavior behavior = d as ListBoxSelectionBehavior;

            if(behavior.modelHandled)
            {
                return;
            }

            if(behavior.AssociatedObject == null)
            {
                return;
            }

            behavior.modelHandled = true;

            behavior.UpdateSelectedValues();

            behavior.SelectItems();

            behavior.modelHandled = false;
        }

        #endregion
        #region 선택 값 리스트 속성 변경시 콜백 처리하기 - SelectedValuesPropertyChangedCallback(d, e)

        /// <summary>
        /// 선택 값 리스트 속성 변경시 콜백 처리하기
        /// </summary>
        /// <param name="d">의존 객체</param>
        /// <param name="e">이벤트 인자</param>
        private static void SelectedValuesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ListBoxSelectionBehavior behavior = d as ListBoxSelectionBehavior;

            if(behavior.modelHandled)
            {
                return;
            }

            if(behavior.AssociatedObject == null)
            {
                return;
            }

            behavior.modelHandled = true;

            behavior.UpdateSelectedItems();

            behavior.SelectItems();

            behavior.modelHandled = false;
        }

        #endregion
        #region 속성 값 구하기 - GetPropertyValue(source, path)

        /// <summary>
        /// 속성 값 구하기
        /// </summary>
        /// <param name="source">소스 객체</param>
        /// <param name="path">경로</param>
        /// <returns>속성 값</returns>
        private static object GetPropertyValue(object source, string path)
        {
            if(string.IsNullOrWhiteSpace(path))
            {
                return source;
            }

            while(true)
            {
                if(path.Contains('.'))
                {
                    string[] pathItemArray = path.Split('.');

                    string remainingProperty = path.Substring(path.IndexOf('.') + 1);

                    source = source?.GetType().GetProperty(pathItemArray[0])?.GetValue(source, null);

                    path = remainingProperty;

                    continue;
                }

                return source?.GetType().GetProperty(path)?.GetValue(source, null);
            }
        }

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////// Instance
        //////////////////////////////////////////////////////////////////////////////// Protected
        ////////////////////////////////////////////////////////////////////// Function

        #region 접착시 처리하기 - OnAttached()

        /// <summary>
        /// 접착시 처리하기
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.SelectionChanged += ListBox_SelectionChanged;

            ((INotifyCollectionChanged)AssociatedObject.Items).CollectionChanged += ListBox_CollectionChanged;

            this.modelHandled = true;

            UpdateSelectedItems();

            SelectItems();

            this.modelHandled = false;
        }

        #endregion
        #region 탈착시 처리하기 - OnDetaching()

        /// <summary>
        /// 탈착시 처리하기
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();

            if(AssociatedObject != null)
            {
                AssociatedObject.SelectionChanged -= ListBox_SelectionChanged;

                ((INotifyCollectionChanged)AssociatedObject.Items).CollectionChanged -= ListBox_CollectionChanged;
            }
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////// Private
        ////////////////////////////////////////////////////////////////////// Event

        #region 리스트 박스 선택 변경시 처리하기 - ListBox_SelectionChanged(sender, e)

        /// <summary>
        /// 리스트 박스 선택 변경시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(this.viewHandled)
            {
                return;
            }

            if(AssociatedObject.Items.SourceCollection == null)
            {
                return;
            }

            SelectedItems = AssociatedObject.SelectedItems.Cast<object>().ToObservableCollection();
        }

        #endregion
        #region 리스트 박스 컬렉션 변경시 처리하기 - ListBox_CollectionChanged(sender, e)

        /// <summary>
        /// 리스트 박스 컬렉션 변경시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void ListBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if(this.viewHandled)
            {
                return;
            }

            if(AssociatedObject.Items.SourceCollection == null)
            {
                return;
            }

            SelectItems();
        }

        #endregion

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

        #region 항목 선택하기 - SelectItems()

        /// <summary>
        /// 항목 선택하기
        /// </summary>
        /// <remarks>속성을 기준으로 리스트 박스에서 항목을 선택합니다</remarks>
        private void SelectItems()
        {
            this.viewHandled = true;

            AssociatedObject.SelectedItems.Clear();

            if(SelectedItems != null)
            {
                foreach(object item in SelectedItems)
                {
                    AssociatedObject.SelectedItems.Add(item);
                }
            }

            this.viewHandled = false;
        }

        #endregion
        #region 선택 항목 리스트 업데이트하기 - UpdateSelectedItems()

        /// <summary>
        /// 선택 항목 리스트 업데이트하기
        /// </summary>
        /// <remarks>SelectedValues 속성값을 기반으로 SelectedItems 속성값을 업데이트 한다.</remarks>
        private void UpdateSelectedItems()
        {
            if(SelectedValues == null)
            {
                SelectedItems = null;
            }
            else
            {
                SelectedItems = AssociatedObject.Items.Cast<object>()
                    .Where(i => SelectedValues.Contains(GetPropertyValue(i, AssociatedObject.SelectedValuePath)))
                    .ToArray();
            }
        }

        #endregion
        #region 선택 값 리스트 업데이트하기 - UpdateSelectedValues()

        /// <summary>
        /// 선택 값 리스트 업데이트하기
        /// </summary>
        /// <remarks>SelectedItems 속성값을 기반으로 SelectedValues 속성값을 업데이트한다.</remarks>
        private void UpdateSelectedValues()
        {
            if(SelectedItems == null)
            {
                SelectedValues = null;
            }
            else
            {
                SelectedValues = SelectedItems.Cast<object>()
                        .Select(i => GetPropertyValue(i, AssociatedObject.SelectedValuePath))
                        .ToArray();
            }
        }

        #endregion
    }
}

 

300x250

 

▶ MainWindowViewModel.cs

using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace TestProject
{
    /// <summary>
    /// 메인 윈도우 뷰 모델
    /// </summary>
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Event
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 속성 변경시 이벤트 - PropertyChanged

        /// <summary>
        /// 속성 변경시 이벤트
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 제목
        /// </summary>
        private string title = "Behavior<T> 클래스 : 리스트 박스 선택 동작 사용하기";

        /// <summary>
        /// 성명 리스트
        /// </summary>
        private IList nameList = null;

        /// <summary>
        /// 선택 성명 리스트
        /// </summary>
        private IList selectedNameList = null;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 제목 - Title

        /// <summary>
        /// 제목
        /// </summary>
        public string Title
        {
            get
            {
                return this.title;
            }
            set
            {
                this.title = value;

                FirePropertyChangedEvent(nameof(Title));
            }
        }

        #endregion

        #region 성명 리스트 - NameList

        /// <summary>
        /// 성명 리스트
        /// </summary>
        public IList NameList
        {
            get
            {
                return this.nameList;
            }
            set
            {
                this.nameList = value;

                FirePropertyChangedEvent(nameof(NameList));
            }
        }

        #endregion
        #region 선택 성명 리스트 - SelectedNameList

        /// <summary>
        /// 선택 성명 리스트
        /// </summary>
        public IList SelectedNameList
        {
            get
            {
                return this.selectedNameList;
            }
            set
            {
                this.selectedNameList = value;

                FirePropertyChangedEvent(nameof(SelectedNameList));
            }
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainWindowViewModel()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainWindowViewModel()
        {
            ObservableCollection<string> nameCollection = new ObservableCollection<string>();

            nameCollection.Add("홍길동");
            nameCollection.Add("김철수");
            nameCollection.Add("이영희");
            nameCollection.Add("김순희");

            this.nameList = nameCollection;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Protected

        #region 속성 변경시 이벤트 발생시키기 - FirePropertyChangedEvent(propertyName)

        /// <summary>
        /// 속성 변경시 이벤트 발생시키기
        /// </summary>
        /// <param name="propertyName">속성명</param>
        protected void FirePropertyChangedEvent(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}

 

▶ 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:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:TestProject"
    Width="800"
    Height="600"
    Title="{Binding Title}"
    FontFamily="나눔고딕코딩"
    FontSize="16">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"    />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*"    />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"    />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*"    />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*"    />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="1" Grid.Column="1"
            Margin="10"
            FontWeight="Bold"
            Text="소스 데이터" />
        <ListBox Name="sourceListBox" Grid.Row="2" Grid.Column="1"
            Width="200"
            Height="300"
            SelectionMode="Extended"
            ItemsSource="{Binding NameList}">
            <i:Interaction.Behaviors>
                <local:ListBoxSelectionBehavior SelectedItems="{Binding SelectedNameList}" />
            </i:Interaction.Behaviors>
        </ListBox>
        <TextBlock Grid.Row="1" Grid.Column="3"
            Margin="10"
            FontWeight="Bold"
            Text="선택 데이터" />
        <ListBox Name="selectedListBox" Grid.Row="2" Grid.Column="3"
            Width="200"
            Height="300"
            ItemsSource="{Binding SelectedNameList}" />
    </Grid>
</Window>

 

▶ MainWindow.xaml.cs

using System.Windows;

namespace TestProject
{
    /// <summary>
    /// 메인 윈도우
    /// </summary>
    public partial class MainWindow : Window
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainWindow()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new MainWindowViewModel();
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요