■ Behavior<T> 클래스를 사용해 리스트 박스 선택 동작을 만드는 방법을 보여준다.
▶ LinqExtension.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
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 } } |
▶ ListBoxSelectionBehavior.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 |
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 } } |
▶ MainWindowViewModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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 } } |