آموزش ساخت AutoCompleteTextBox در WPF
در این بخش آموزش ساخت AutoCompleteTextBox در WPF را برای شما آماده کرده ایم که یک آموزش مناسب برای ساخت کنترل های سفارشی با استفاده از زبان برنامه نویسی سی شارپ و تکنولوژی Xaml است. در ادامه می توانید توضیحات، تصاویر و فیلمی از نتیجه نهایی را مشاهده کنید. همچنین سورس کد پروژه نیز به صورت رایگان برای دانلود قرار داده شده است.
توضیحات
برای ساخت این پروژه از نرم افزار Visual Studio نسخه ۲۰۱۹ و فریم ورک .Net Core 3.1 استفاده شده است. البته شما می توانید با اعمال تغییرات کوچکی پروژه را در نسخه های پایین تر نیز پیاده سازی کنید. نتیجه نهایی به شکل زیر خواهد بود.
مراحل آموزش
- ایجاد پروژه WPF Custom Control Library
- ایجاد کنترل AutoCompleteTextField
- ایجاد پروژه WPF
- استفاده از کنترل AutoCompleteTextField
ایجاد پروژه WPF Custom Control Library
ابتدا یک Blank Solution ایجاد کنید و سپس یک پروژه از نوع WPF Custom Control Library به آن اضافه کنید.
ایجاد کنترل AutoCompleteTextField
بعد از ایجاد شدن پروژه Custom Control Library آیتم هایی به صورت پیش فرض ایجاد می شوند را پاک کنید و یک آیتم جدید از نوع Custom Control با نام AutoCompleteTextField را به پروژه اضافه کنید. سپس محتوای فایل AutoCompleteTextField.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 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 | using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; namespace AutoCompleteTextBox { public class AutoCompleteTextField : Control { #region Fields private const string TextBoxPartName = "PART_TextBox"; private const string PopupTextBoxPartName = "PART_PopupTextBox"; private const string SuggestionPopupPartName = "PART_SuggestionPopup"; private const string SuggestionListBoxPartName = "PART_SuggestionListBox"; private TextBox _textBox; private TextBox _popupTextBox; private Popup _suggestionPopup; private ListBox _suggestionListBox; #endregion #region Constructors static AutoCompleteTextField() { DefaultStyleKeyProperty.OverrideMetadata(typeof(AutoCompleteTextField), new FrameworkPropertyMetadata(typeof(AutoCompleteTextField))); } public AutoCompleteTextField() { Loaded += (sender, args) => RegisterEventHandlers(); Unloaded += (sender, args) => UnregisterEventHandlers(); } #endregion #region Base methods public override void OnApplyTemplate() { base.OnApplyTemplate(); LoadControls(); var selectItemCommandBinding = new CommandBinding(SelectItemCommand, HandleSelectItemCommand); CommandBindings.Add(selectItemCommandBinding); } protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); _textBox.Focus(); } #endregion #region Static commands public static RoutedCommand SelectItemCommand = new RoutedCommand(); #endregion #region Command handlers private void HandleSelectItemCommand(object sender, ExecutedRoutedEventArgs e) { _suggestionListBox.SelectedItem = e.Parameter; OnItemSelected(); } #endregion #region Helper methods private void LoadControls() { _textBox = GetTemplateChild(TextBoxPartName) as TextBox; _suggestionPopup = GetTemplateChild(SuggestionPopupPartName) as Popup; _popupTextBox = GetTemplateChild(PopupTextBoxPartName) as TextBox; _suggestionListBox = GetTemplateChild(SuggestionListBoxPartName) as ListBox; } private void RegisterEventHandlers() { PreviewKeyDown += OnPreviewKeyDown; KeyDown += OnKeyDown; _textBox.GotMouseCapture += OnTextBoxGotMouseCapture; _textBox.TextChanged += OnTextBoxTextChanged; _textBox.PreviewKeyDown += OnTextBoxPreviewKeyDown; _popupTextBox.PreviewKeyDown += OnPopupTextBoxPreviewKeyDown; _suggestionPopup.Opened += OnSuggestionPopupOpened; _suggestionPopup.Closed += OnSuggestionPopupClosed; } private void UnregisterEventHandlers() { PreviewKeyDown -= OnPreviewKeyDown; _textBox.GotMouseCapture -= OnTextBoxGotMouseCapture; _textBox.TextChanged -= OnTextBoxTextChanged; _textBox.PreviewKeyDown -= OnTextBoxPreviewKeyDown; _popupTextBox.PreviewKeyDown -= OnPopupTextBoxPreviewKeyDown; _suggestionPopup.Opened -= OnSuggestionPopupOpened; _suggestionPopup.Closed -= OnSuggestionPopupClosed; } private string GetSelectedItem() => (_suggestionListBox.SelectedItem as AutoCompleteTextFieldMatchResult).Item; private void OnItemSelected() { _textBox.Text = GetSelectedItem(); _textBox.CaretIndex = _textBox.Text.Length; _textBox.Focus(); _suggestionPopup.IsOpen = false; if (ItemSelectionCommand is null) return; if (ItemSelectionCommand.CanExecute(Text)) { ItemSelectionCommand.Execute(Text); ClosePopup(); } } private void ClosePopup() { _suggestionListBox.ItemsSource = null; _suggestionPopup.IsOpen = false; } private void CreateSuggestion() { if (!IsLoaded) return; if (ItemsSource is null || ItemsSource.Count() == 0) { ClosePopup(); return; } var value = _textBox.Text.ToLower(); var filteredItems = new List<AutoCompleteTextFieldMatchResult>(); ItemsSource.ToList().ForEach(i => { var matchInfo = IsMatch(value, i.ToLower()); if (matchInfo.Percentage >= MinimumMatchPercentage) filteredItems.Add(matchInfo); }); filteredItems = filteredItems.OrderByDescending(i => i.Percentage).Take(MaxSuggestionItems).ToList(); if (filteredItems.Count() == 1 && filteredItems.First().Item.Equals(_textBox.Text, StringComparison.OrdinalIgnoreCase)) { ClosePopup(); return; } if (filteredItems.Count() > 0) { _suggestionListBox.ItemsSource = filteredItems; _suggestionListBox.SelectedIndex = 0; _suggestionPopup.IsOpen = true; return; } ClosePopup(); } private AutoCompleteTextFieldMatchResult IsMatch(string input, string suggestedItem) { var inputWords = input.Split(' '); var totalMatchPercentage = inputWords.Length * 100; var matchedWords = new List<AutoCompleteTextFieldMatchResult>(); foreach (var inputWord in inputWords) { var matchInfo = GetWordMatchInfo(inputWord, suggestedItem); matchedWords.Add(matchInfo); } var matchedWordsPercentage = matchedWords.Sum(i => i.Percentage); var percentage = (matchedWordsPercentage * 100) / totalMatchPercentage; return new AutoCompleteTextFieldMatchResult { Percentage = percentage, Item = suggestedItem }; } private AutoCompleteTextFieldMatchResult GetWordMatchInfo(string input, string suggestedItem) { var inputChars = input.ToCharArray(); var suggestedItemWords = suggestedItem.Split(' '); var matchInfo = new AutoCompleteTextFieldMatchResult(); foreach (var word in suggestedItemWords) { if (input == word) { matchInfo.Percentage = 100; return matchInfo; } if (word.Length < input.Length) continue; var wordChars = word.ToCharArray(); var matchCount = GetMatchCount(inputChars, wordChars); var matchPercentage = matchCount * 100 / wordChars.Length; if (matchCount > 1) { matchInfo.Percentage = matchPercentage; return matchInfo; } } return matchInfo; } private static int GetMatchCount(char[] input, char[] word) { if (input.Length == 0 || word.Length == 0) return 0; int counter; for (var i = 0; i < word.Length; i++) { counter = 0; if (word[i] != input[0]) continue; for (int j = 0, k = i; j < input.Length; j++, k++) { if (k < word.Length && word[k] == input[j]) counter++; } if (counter == input.Length) return counter; } return 0; } #endregion #region Event handlers private void OnPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter && _suggestionPopup.IsOpen) { OnItemSelected(); return; } if (e.Key == Key.Escape) { ClosePopup(); return; } } private void OnKeyDown(object sender, KeyEventArgs e) { if (SubmitByEnterCommand is null || e.Key != Key.Return) return; if (SubmitByEnterCommand.CanExecute(Text)) { SubmitByEnterCommand.Execute(Text); ClosePopup(); } } private void OnTextBoxPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space && e.KeyboardDevice.Modifiers == ModifierKeys.Control) { e.Handled = true; CreateSuggestion(); return; } } private void OnPopupTextBoxPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Down && _suggestionListBox.Items.Count > 0) { _suggestionPopup.IsOpen = true; if (_suggestionListBox.SelectedIndex < _suggestionListBox.Items.Count) _suggestionListBox.SelectedIndex++; return; } if (e.Key == Key.Up && _suggestionListBox.Items.Count > 0) { _suggestionPopup.IsOpen = true; if (_suggestionListBox.SelectedIndex > 0) _suggestionListBox.SelectedIndex--; return; } } private void OnTextBoxGotMouseCapture(object sender, MouseEventArgs e) { if (_suggestionPopup.IsOpen) return; if (_suggestionListBox.Items.Count > 0) { _suggestionPopup.IsOpen = true; _popupTextBox.CaptureMouse(); } } private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e) { CreateSuggestion(); } private void OnSuggestionPopupOpened(object sender, EventArgs e) { _popupTextBox.CaretIndex = _popupTextBox.Text.Length; _popupTextBox.Focus(); } private void OnSuggestionPopupClosed(object sender, EventArgs e) { _textBox.CaretIndex = _popupTextBox.Text.Length; _textBox.Focus(); } #endregion #region DependencyProperty : ItemsSource public IEnumerable<string> ItemsSource { get { return (IEnumerable<string>)GetValue(ItemsSourceProperty); } set { SetValue(ItemsSourceProperty, value); } } public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(nameof(ItemsSource), typeof(IEnumerable<string>), typeof(AutoCompleteTextField), new UIPropertyMetadata(default, OnItemsSourceChanged)); private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is AutoCompleteTextField autoCompleteTextField) autoCompleteTextField.CreateSuggestion(); } #endregion #region DependencyProperty : MinimumMatchPercentage public int MinimumMatchPercentage { get { return (int)GetValue(MinimumMatchPercentageProperty); } set { SetValue(MinimumMatchPercentageProperty, value); } } public static readonly DependencyProperty MinimumMatchPercentageProperty = DependencyProperty.Register(nameof(MinimumMatchPercentage), typeof(int), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion #region DependencyProperty : MaxSuggestionItems public int MaxSuggestionItems { get { return (int)GetValue(MaxSuggestionItemsProperty); } set { SetValue(MaxSuggestionItemsProperty, value); } } public static readonly DependencyProperty MaxSuggestionItemsProperty = DependencyProperty.Register(nameof(MaxSuggestionItems), typeof(int), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion #region DependencyProperty : Text public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(AutoCompleteTextField), new FrameworkPropertyMetadata(default, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); #endregion #region DependencyProperty : Hint public object Hint { get { return GetValue(HintProperty); } set { SetValue(HintProperty, value); } } public static readonly DependencyProperty HintProperty = DependencyProperty.Register(nameof(Hint), typeof(object), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion #region DependencyProperty : CornerRadius public CornerRadius CornerRadius { get { return (CornerRadius)GetValue(CornerRadiusProperty); } set { SetValue(CornerRadiusProperty, value); } } public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(nameof(CornerRadius), typeof(CornerRadius), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion #region DependencyProperty : RemoveItemCommand public ICommand RemoveItemCommand { get { return (ICommand)GetValue(RemoveItemCommandProperty); } set { SetValue(RemoveItemCommandProperty, value); } } public static readonly DependencyProperty RemoveItemCommandProperty = DependencyProperty.Register(nameof(RemoveItemCommand), typeof(ICommand), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion #region DependencyProperty : SubmitByEnterCommand public ICommand SubmitByEnterCommand { get { return (ICommand)GetValue(SubmitByEnterCommandProperty); } set { SetValue(SubmitByEnterCommandProperty, value); } } public static readonly DependencyProperty SubmitByEnterCommandProperty = DependencyProperty.Register(nameof(SubmitByEnterCommand), typeof(ICommand), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion #region DependencyProperty : ItemSelectionCommand public ICommand ItemSelectionCommand { get { return (ICommand)GetValue(ItemSelectionCommandProperty); } set { SetValue(ItemSelectionCommandProperty, value); } } public static readonly DependencyProperty ItemSelectionCommandProperty = DependencyProperty.Register(nameof(ItemSelectionCommand), typeof(ICommand), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion #region DependencyProperty : ListBoxSelectedItemBackground public Brush ListBoxSelectedItemBackground { get { return (Brush)GetValue(ListBoxSelectedItemBackgroundProperty); } set { SetValue(ListBoxSelectedItemBackgroundProperty, value); } } public static readonly DependencyProperty ListBoxSelectedItemBackgroundProperty = DependencyProperty.Register(nameof(ListBoxSelectedItemBackground), typeof(Brush), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion #region DependencyProperty : ListBoxItemMouseOverBackground public Brush ListBoxItemMouseOverBackground { get { return (Brush)GetValue(ListBoxItemMouseOverBackgroundProperty); } set { SetValue(ListBoxItemMouseOverBackgroundProperty, value); } } public static readonly DependencyProperty ListBoxItemMouseOverBackgroundProperty = DependencyProperty.Register(nameof(ListBoxItemMouseOverBackground), typeof(Brush), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion #region DependencyProperty : SuggestionListMaxHeight public double SuggestionListMaxHeight { get { return (double)GetValue(SuggestionListMaxHeightProperty); } set { SetValue(SuggestionListMaxHeightProperty, value); } } public static readonly DependencyProperty SuggestionListMaxHeightProperty = DependencyProperty.Register(nameof(SuggestionListMaxHeight), typeof(double), typeof(AutoCompleteTextField), new UIPropertyMetadata(default)); #endregion } } |
بعد از آن یک کلاس جدید با نام AutoCompleteTextFieldMatchResult.cs ایجاد کرده و محتوای آن را به شکل زیر تغییر دهید.
1 2 3 4 5 6 7 8 | namespace AutoCompleteTextBox { internal class AutoCompleteTextFieldMatchResult { public string Item { get; set; } public int Percentage { get; set; } } } |
این کلاس برای برای ایجاد لیست پیشنهادی برای کنترل سفارشی ما استفاده می شود. برای ظاهر کنترل هم ابتدا یک Converter مانند نمونه زیر ایجاد کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace AutoCompleteTextBox.Converters { internal class AutoCompleteTextFieldPaddingToPopupMarginConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var padding = (Thickness)value; return new Thickness(padding.Left, 0, padding.Right, 0); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => Binding.DoNothing; } } |
این تبدیل کننده برای تنظیم مقدار Margin فیلد موجود در داخل Popup استفاده می شود. حال باید ظاهر کنترل را درست کنیم. برای اینکار فایل 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 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 | <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:po="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:local="clr-namespace:AutoCompleteTextBox" xmlns:system="clr-namespace:System;assembly=System.Runtime" xmlns:converters="clr-namespace:AutoCompleteTextBox.Converters"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary> <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> <converters:AutoCompleteTextFieldPaddingToPopupMarginConverter x:Key="AutoCompleteTextFieldPaddingToPopupMarginConverter" /> </ResourceDictionary> </ResourceDictionary.MergedDictionaries> <system:Double x:Key="IconSize">16</system:Double> <DropShadowEffect x:Key="AutoCompleteTextFieldPopupBorderShadow" BlurRadius="8" ShadowDepth="2.25" Opacity=".42" RenderingBias="Performance" po:Freeze="True"/> <DataTemplate x:Key="AutoCompleteTextFieldRemoveButtonContentTemplate"> <Viewbox> <Canvas Width="2048" Height="2048"> <Path Fill="{Binding Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" Data="M1718.1,1534.2c18.9,18.9,18.9,49.6,0,68.5l-115.4,115.4c-18.9,18.9-49.6,18.9-68.5,0L1024,1207.8l-510.2,510.2c-18.9,18.9-49.6,18.9-68.5,0l-115.4-115.4c-18.9-18.9-18.9-49.6,0-68.5L840.2,1024L329.9,513.8c-18.9-18.9-18.9-49.6,0-68.5l115.4-115.4c18.9-18.9,49.6-18.9,68.5,0L1024,840.2l510.2-510.2c18.9-18.9,49.6-18.9,68.5,0l115.4,115.4c18.9,18.9,18.9,49.6,0,68.5L1207.8,1024L1718.1,1534.2z"/> </Canvas> </Viewbox> </DataTemplate> <Style x:Key="AutoCompleteTextFieldRemoveButtonStyle" TargetType="{x:Type Button}"> <Setter Property="UseLayoutRounding" Value="True"/> <Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Cursor" Value="Hand" /> <Setter Property="Background" Value="Transparent" /> <Setter Property="BorderBrush" Value="Transparent" /> <Setter Property="BorderThickness" Value="0" /> <Setter Property="Focusable" Value="False" /> <Setter Property="Padding" Value="8,0" /> <Setter Property="Margin" Value="0,0,4,0" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Border x:Name="ContainerBorder" UseLayoutRounding="True" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ContentPresenter x:Name="ContentPresenter" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="{TemplateBinding Padding}" RenderOptions.ClearTypeHint="Auto" TextOptions.TextRenderingMode="Auto" TextOptions.TextFormattingMode="Display" Opacity="0.64"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Opacity" TargetName="ContainerBorder" Value="0.42"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Opacity" TargetName="ContentPresenter" Value="1"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="AutoCompleteTextFieldTextBoxStyle" TargetType="{x:Type TextBox}"> <Setter Property="Background" Value="Transparent" /> <Setter Property="BorderBrush" Value="Transparent" /> <Setter Property="BorderThickness" Value="0" /> <Setter Property="VerticalContentAlignment" Value="Center" /> <Setter Property="CaretBrush" Value="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Foreground}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBox}"> <Border CornerRadius="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:AutoCompleteTextField}, Path=CornerRadius}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"> <ScrollViewer x:Name="PART_ContentHost" Margin="{TemplateBinding Padding}"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="AutoCompleteTextFieldPopupStyle" TargetType="{x:Type Popup}"> <Setter Property="StaysOpen" Value="False" /> <Setter Property="AllowsTransparency" Value="True" /> <Setter Property="PopupAnimation" Value="Fade" /> <Setter Property="Placement" Value="Relative" /> </Style> <Style x:Key="AutoCompleteTextFieldListBoxItemStyle" TargetType="{x:Type ListBoxItem}"> <Setter Property="UseLayoutRounding" Value="True" /> <Setter Property="OverridesDefaultStyle" Value="True" /> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="VerticalContentAlignment" Value="Center" /> <Setter Property="Padding" Value="6" /> <Setter Property="Height" Value="Auto" /> <Setter Property="MinHeight" Value="38" /> <Setter Property="FocusVisualStyle" Value="{x:Null}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"> <Border.InputBindings> <MouseBinding Gesture="LeftClick" CommandParameter="{Binding}" Command="{x:Static local:AutoCompleteTextField.SelectItemCommand}" /> </Border.InputBindings> <Grid VerticalAlignment="{TemplateBinding VerticalContentAlignment}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Viewbox Grid.Column="0" Margin="12,0" Opacity="0.64" Width="{StaticResource IconSize}" Height="{StaticResource IconSize}"> <Canvas Width="24" Height="24"> <Path Fill="{TemplateBinding Foreground}" Data="M12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22C6.47,22 2,17.5 2,12A10,10 0 0,1 12,2M12.5,7V12.25L17,14.92L16.25,16.15L11,13V7H12.5Z" /> </Canvas> </Viewbox> <TextBlock Grid.Column="1" Margin="{TemplateBinding Padding}" Text="{Binding Item}" ToolTip="{Binding Item}" VerticalAlignment="Center" TextTrimming="WordEllipsis"/> <Button x:Name="RemoveButton" Grid.Column="2" Visibility="Collapsed" CommandParameter="{Binding Item}" Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:AutoCompleteTextField}, Path=RemoveItemCommand}" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" Style="{StaticResource AutoCompleteTextFieldRemoveButtonStyle}"> <Button.ContentTemplate> <DataTemplate> <ContentControl ContentTemplate="{StaticResource AutoCompleteTextFieldRemoveButtonContentTemplate}" Width="{StaticResource IconSize}" Height="{StaticResource IconSize}"/> </DataTemplate> </Button.ContentTemplate> </Button> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:AutoCompleteTextField}}, Path=ListBoxSelectedItemBackground}" /> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:AutoCompleteTextField}}, Path=ListBoxItemMouseOverBackground}" /> <Setter TargetName="RemoveButton" Property="Visibility" Value="Visible" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="AutoCompleteTextFieldListBoxStyle" TargetType="{x:Type ListBox}"> <Setter Property="Background" Value="Transparent" /> <Setter Property="BorderThickness" Value="0" /> <Setter Property="Padding" Value="0" /> <Setter Property="Margin" Value="0,12" /> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" /> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" /> <Setter Property="FocusVisualStyle" Value="{x:Null}" /> <Style.Resources> <Style TargetType="Border"> <Setter Property="CornerRadius" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:AutoCompleteTextField}}, Path=CornerRadius}"/> </Style> </Style.Resources> </Style> <Style TargetType="{x:Type local:AutoCompleteTextField}"> <Setter Property="UseLayoutRounding" Value="True" /> <Setter Property="MinimumMatchPercentage" Value="50" /> <Setter Property="MaxSuggestionItems" Value="5" /> <Setter Property="VerticalContentAlignment" Value="Center" /> <Setter Property="Background" Value="#f6f6f6" /> <Setter Property="ListBoxSelectedItemBackground" Value="#f0f0f0" /> <Setter Property="ListBoxItemMouseOverBackground" Value="#e0e0e0" /> <Setter Property="FontSize" Value="14" /> <Setter Property="CornerRadius" Value="6" /> <Setter Property="Padding" Value="6,0" /> <Setter Property="Height" Value="Auto" /> <Setter Property="MinHeight" Value="38" /> <Setter Property="Cursor" Value="IBeam" /> <Setter Property="Focusable" Value="False" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:AutoCompleteTextField}"> <Border x:Name="PART_ContainerBorder" CornerRadius="{TemplateBinding CornerRadius}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <Grid Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"> <ContentPresenter x:Name="PART_HintPresenter" Cursor="IBeam" Opacity="0.64" TextBlock.TextAlignment="{Binding ElementName=PART_TextBox, Path=TextAlignment}" Visibility="{Binding ElementName=PART_TextBox, Path=Text.IsEmpty, Converter={StaticResource BooleanToVisibilityConverter}}" Content="{TemplateBinding Hint}" /> <TextBox x:Name="PART_TextBox" Foreground="{TemplateBinding Foreground}" Style="{StaticResource AutoCompleteTextFieldTextBoxStyle}" Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> <Popup x:Name="PART_SuggestionPopup" PlacementTarget="{Binding ElementName=PART_ContainerBorder}" Style="{StaticResource AutoCompleteTextFieldPopupStyle}"> <Border Margin="8" Effect="{StaticResource AutoCompleteTextFieldPopupBorderShadow}" CornerRadius="{TemplateBinding CornerRadius}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <StackPanel Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:AutoCompleteTextField}}, Path=ActualWidth}"> <Grid Margin="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Padding, Converter={StaticResource AutoCompleteTextFieldPaddingToPopupMarginConverter}}"> <ContentPresenter Cursor="IBeam" Opacity="0.64" VerticalAlignment="Center" Margin="{Binding ElementName=PART_HintPresenter, Path=Margin}" TextBlock.TextAlignment="{Binding ElementName=PART_TextBox, Path=TextAlignment}" Visibility="{Binding ElementName=PART_TextBox, Path=Text.IsEmpty, Converter={StaticResource BooleanToVisibilityConverter}}" Content="{TemplateBinding Hint}" /> <TextBox x:Name="PART_PopupTextBox" Margin="{Binding ElementName=PART_TextBox, Path=Margin}" Foreground="{TemplateBinding Foreground}" Height="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:AutoCompleteTextField}}, Path=ActualHeight}" Style="{StaticResource AutoCompleteTextFieldTextBoxStyle}" Text="{Binding ElementName=PART_TextBox, Path=Text, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> </Grid> <Separator BorderBrush="{TemplateBinding Foreground}" BorderThickness="2" Opacity="0.2" Margin="12,0"/> <ListBox x:Name="PART_SuggestionListBox" Foreground="{TemplateBinding Foreground}" Background="{TemplateBinding Background}" MaxHeight="{TemplateBinding SuggestionListMaxHeight}" ItemContainerStyle="{StaticResource AutoCompleteTextFieldListBoxItemStyle}" Style="{StaticResource AutoCompleteTextFieldListBoxStyle}" /> </StackPanel> </Border> </Popup> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
در ادامه بخش های مختلف کد بالا را بررسی میکنیم. تکه کد زیر مربوط به تعریف Converter ها است که BooleanToVisibilityConverter به صورت پیشفرض (Built-in) در WPF وجود دارد و AutoCompleteTextFieldPaddingToPopupMarginConverter هم تبدیل کننده ای است که خودمان ایجاد کرده ایم.
1 2 3 4 5 6 | <ResourceDictionary.MergedDictionaries> <ResourceDictionary> <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> <converters:AutoCompleteTextFieldPaddingToPopupMarginConverter x:Key="AutoCompleteTextFieldPaddingToPopupMarginConverter" /> </ResourceDictionary> </ResourceDictionary.MergedDictionaries> |
تکه کد زیر مربوط به اندازه آیکون های حذف و تاریخچه است که برای هر یک از آیتم های پیشنهادی نمایش داده می شوند.
1 | <system:Double x:Key="IconSize">16</system:Double> |
تکه کد زیر مربوط به افکت سایه Popup است.
1 2 3 4 5 6 7 | <DropShadowEffect x:Key="AutoCompleteTextFieldPopupBorderShadow" BlurRadius="8" ShadowDepth="2.25" Opacity=".42" RenderingBias="Performance" po:Freeze="True"/> |
تکه کد زیر قالب مربوط به آیکون حذف آیتم از لیست پیشنهادی است.
1 2 3 4 5 6 7 8 9 | <DataTemplate x:Key="AutoCompleteTextFieldRemoveButtonContentTemplate"> <Viewbox> <Canvas Width="2048" Height="2048"> <Path Fill="{Binding Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" Data="M1718.1,1534.2c18.9,18.9,18.9,49.6,0,68.5l-115.4,115.4c-18.9,18.9-49.6,18.9-68.5,0L1024,1207.8l-510.2,510.2c-18.9,18.9-49.6,18.9-68.5,0l-115.4-115.4c-18.9-18.9-18.9-49.6,0-68.5L840.2,1024L329.9,513.8c-18.9-18.9-18.9-49.6,0-68.5l115.4-115.4c18.9-18.9,49.6-18.9,68.5,0L1024,840.2l510.2-510.2c18.9-18.9,49.6-18.9,68.5,0l115.4,115.4c18.9,18.9,18.9,49.6,0,68.5L1207.8,1024L1718.1,1534.2z"/> </Canvas> </Viewbox> </DataTemplate> |
استایل ها
- AutoCompleteTextFieldRemoveButtonStyle: استایل مربوط به دکمه حذف آیتم از لیست پیشنهادی.
- AutoCompleteTextFieldTextBoxStyle: استایل مربوط به TextBox های موجود در داخل کنترل AutoCompleteTextField.
- AutoCompleteTextFieldPopupStyle: استایل مربوط به Popup که لیست پیشنهادی در داخل آن نمایش داده می شود.
- AutoCompleteTextFieldListBoxItemStyle: استایل مربوط به آیتم های ListBox.
- AutoCompleteTextFieldListBoxStyle: استایل مربوط به ListBox.
و در آخر هم قالب مربوط به کنترل AutoCompleteTextField قرار دارد که از موارد گفته شده در بالا در داخل آن استفاده شده است. اگر در درک بخشی از کدهای بالا مشکل داشتید میتوانید در قسمت نظرات یا انجمن سایت مطرح کنید تا برای شما توضیح داده شود.
ایجاد پروژه WPF
برای تست کنترلی که ایجاد کرده ایم، یک پروژه از نوع WPF با نام AutoCompleteTextBox.Demo اضافه کنید. و سپس Reference مربوط به پروژه WPF Custom Control Library را به آن اضافه کنید.
استفاده از کنترل AutoCompleteTextField
بعد از انجام مرحله بالا، فایل App.xaml را باز کنید و Resource مربوط به کنترل سفارشی را به شکل زیر به آن اضافه کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <Application x:Class="AutoCompleteTextBox.Demo.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/AutoCompleteTextBox;component/Themes/Generic.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
سپس یک کلاس جدید با نام RelayCommand.cs اضافه کنید و محتوای آن را به شکل زیر تغییر دهید. این کلاس برای هندل کردن Command ها استفاده می شود.
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 | using System; using System.Diagnostics; using System.Windows.Input; namespace AutoCompleteTextBox.Demo { public class RelayCommand : ICommand { #region Fields private readonly Action<object> _execute; private readonly Predicate<object> _canExecute; #endregion Fields #region Constructors public RelayCommand(Action<object> execute) : this(execute, null) { } public RelayCommand(Action<object> execute, Predicate<object> canExecute) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; } #endregion Constructors #region ICommand Members [DebuggerStepThrough] public bool CanExecute(object parameters) { return _canExecute?.Invoke(parameters) ?? true; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameters) { _execute(parameters); } #endregion ICommand Members } } |
همچنین محتوای فایل های MainWindow.xaml و MainWindow.xaml.cs را به شکل زیر تغییر دهید.
فایل 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 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 | <Window x:Class="AutoCompleteTextBox.Demo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:AutoCompleteTextBox;assembly=AutoCompleteTextBox" mc:Ignorable="d" Title="SourceSara.Com" Height="500" Width="600" MinWidth="600" MinHeight="500" Background="#1B2738" TextElement.FontFamily="Roboto" TextBlock.FontFamily="Roboto" WindowStartupLocation="CenterScreen"> <Window.Resources> <Style TargetType="{x:Type local:AutoCompleteTextField}"> <Setter Property="ListBoxSelectedItemBackground" Value="#323D4C" /> <Setter Property="ListBoxItemMouseOverBackground" Value="#182333" /> <Setter Property="SuggestionListMaxHeight" Value="240" /> <Setter Property="MaxSuggestionItems" Value="5" /> <Setter Property="MinimumMatchPercentage" Value="30" /> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="HorizontalAlignment" Value="Center" /> <Setter Property="Foreground" Value="#fff" /> <Setter Property="Background" Value="#3C4C5E" /> <Setter Property="Margin" Value="16" /> <Setter Property="Width" Value="360" /> <Setter Property="Padding" Value="12" /> <Setter Property="FontSize" Value="16" /> <Setter Property="CornerRadius" Value="16" /> </Style> </Window.Resources> <StackPanel Margin="0,32,0,0"> <TextBlock FontSize="24" Margin="0,24" TextAlignment="Center" Foreground="#8ab4f8" Text="WPF Auto Complete Text Field"/> <Grid HorizontalAlignment="Center" VerticalAlignment="Center" TextBlock.FontSize="16" TextBlock.Foreground="#a0afc0"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Margin="16"> <TextBlock Text="Left to right" Margin="16,0"/> <local:AutoCompleteTextField Hint="Search..." RemoveItemCommand="{Binding LtrDeleteCommand}" ItemsSource="{Binding LtrItems}"/> </StackPanel> <StackPanel Grid.Row="1" Margin="16"> <TextBlock Text="Right to left" Margin="16,0"/> <local:AutoCompleteTextField FlowDirection="RightToLeft" Hint="جستجو..." RemoveItemCommand="{Binding RtlDeleteCommand}" ItemsSource="{Binding RtlItems}"/> </StackPanel> </Grid> <local:MadeByAmRo Margin="0,64,0,0" Foreground="#a0afc0" AmRoLogoBrush="#8ab4f8" HeartBrush="#f28b82"/> </StackPanel> </Window> |
فایل 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 | using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Windows.Input; namespace AutoCompleteTextBox.Demo { public partial class MainWindow : INotifyPropertyChanged { #region Fields private ObservableCollection<string> _ltrItems; private ObservableCollection<string> _rtlItems; #endregion #region Constructors public MainWindow() { InitializeComponent(); AddDummyData(); RegisterCommands(); DataContext = this; } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; #endregion #region Properties public ObservableCollection<string> LtrItems { get => _ltrItems; set { _ltrItems = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LtrItems))); } } public ObservableCollection<string> RtlItems { get => _rtlItems; set { _rtlItems = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(RtlItems))); } } #endregion #region Commands public ICommand LtrDeleteCommand { get; set; } public ICommand RtlDeleteCommand { get; set; } #endregion #region Command handlers private void HandleLtrDeleteCommand(object parameter) { var item = parameter.ToString(); var filteredItems = LtrItems.Where(i => i.ToLower() != item.ToLower()); LtrItems = new ObservableCollection<string>(filteredItems); } private void HandleRtlDeleteCommand(object parameter) { var item = parameter.ToString(); var filteredItems = RtlItems.Where(i => i.ToLower() != item.ToLower()); RtlItems = new ObservableCollection<string>(filteredItems); } #endregion #region Helper methods private void AddDummyData() { LtrItems = new ObservableCollection<string> { "window", "How to connect to sql in c#", "wood", "Good for one", "first", "first time search", "WPF custom text field", "How to create custom window chrome in wpf", "Create radio button with custom functionality in wpf", "Good for one, good for all", "Submit your email address to stay informed", "Open file in c++", "C# display system information", "How to connect to sql server from remote computer", "the best practice for checking internet connection", }; RtlItems = new ObservableCollection<string> { "سلام", "سلام چطوری", "خوبم تو چطوری", "سورس سرا", "سورس کدهای آماده", "انجمن سورس سرا", "سورس بازی مار", "سورس پیام رسان به زبان سی شارپ", "سورس برنامه حساب داری", "سورس بازی شطرنج به زبان سی پلاس پلاس", "دانلود نرم افزار ویژوال استودیو", "دانلود نرم Visual Studio 2019", }; } private void RegisterCommands() { LtrDeleteCommand = new RelayCommand(HandleLtrDeleteCommand); RtlDeleteCommand = new RelayCommand(HandleRtlDeleteCommand); } #endregion } } |
پروژه را Build و Run کنید تا نتیجه نهایی را مشاهده کنید.
هیچ نظری ثبت نشده است