WPF Auto Complete Text Box

A simple and useful control for WPF. It supports Binding and MVVM. 

Features:
  • Supports MVVM for auto suggestions
  • Asynchronously load suggestions
  • Supports watermark
  • Supports Icon

Latest release of AutoCompleteTextBox is available at CodePlex or Visual Studio Gallery.

WPF Auto Complete Text Box

Below is a sample code of FilesystemSuggestionProvider.

Public Class FilesystemSuggestionProvider
    Implements ISuggestionProvider

    Public Function GetSuggestions(ByVal filter As String) As System.Collections.IEnumerable Implements ISuggestionProvider.GetSuggestions
        If String.IsNullOrEmpty(filter) Then
            Return Nothing
        End If
        If filter.Length < 3 Then
            Return Nothing
        End If

        If filter(1) <> ":"c Then
            Return Nothing
        End If

        Dim lst As New List(Of IO.FileSystemInfo)
        Dim dirFilter As String = "*"
        Dim dirPath As String = filter
        If Not filter.EndsWith("\") Then
            Dim index As Integer = filter.LastIndexOf("\")
            dirPath = filter.Substring(0, index + 1)
            dirFilter = filter.Substring(index + 1) + "*"
        End If
        Dim dirInfo As IO.DirectoryInfo = New IO.DirectoryInfo(dirPath)
        lst.AddRange(dirInfo.GetFileSystemInfos(dirFilter))
        Return lst
    End Function

End Class

Adding AutoCompleteTextBox in your view:

<wpf:AutoCompleteTextBox VerticalAlignment="Top"
     Height="25"
     Grid.Column="1"
     Text="{Binding Path=FileName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
     DisplayMember="FullName"
     ItemTemplate="{StaticResource ResourceKey=fsTemplate}"
     Provider="{StaticResource ResourceKey=fsp}" /> 
WPF Transparent TextBox Style

WPF Transparent TextBox Style

Below is the code snippet to create a Transparent TextBox in WPF

Code:
<Style TargetType="{x:Type TextBox}" x:Key="TransparentTextBoxStyle">
    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Grid>
                    <ScrollViewer x:Name="PART_ContentHost"
                                Background="Transparent"
                                Focusable="True"
                                HorizontalScrollBarVisibility="Hidden"
                                VerticalScrollBarVisibility="Hidden" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
Understanding for Loop

Understanding for Loop


Understanding for Loop

Loops are programming language constructs that are used to execute a segment of code repeatedly a number of times.

Syntax:
                for (Initialize Counter; Boolean Expression; Expression)
      {
            // code to execute repeatedly inside the loop
      }

Explain:
For loop has three arguments:
  1. Counter initialization
  2. Boolean expression
  3. Increment/decrement expression (for counter commonly)

Note: All three arguments are optional (you may leave them blank). You may leave any or all the three arguments blank.

For example:
                for (; ; )
      {

      }

  1. Counter Initialization
Counter is a variable that may use to count or limit the number of reputation of the loop.
In this argument the initial value is assigned to the counter. You may leave the argument blank in case the counter is already initialized. The counter initialization executes only the first time the loop executes.

  1. Boolean Expression
Boolean Expression specifies the condition for executing the loop. The loop continues till the Boolean expression is set/returns the true value. When the Boolean expression returns or results to false the loop terminates.

  1. Increment/decrement expression
Increment/decrement expression used to increment or decrement the value of the counter (but not necessarily). You may leave this argument blank or this expression may used to manipulate the value of the variable other than the counter. This expression executes at the end of the loops body.


Some examples explaining the usage of for loop.

int counter;
for (counter = 0; counter < 10; counter++)
{
      System.out.println(counter);
}

Understand the above program.

In the first argument we initialized the value of counter to 0. In the second argument a boolean expression “counter < 10” is supplied to that specifies the condition for executing the loops body. The code inside the loops body execute till the condition satisfies. And the third argument is counter increment expression. This expression will increment the value of counter to 1 at every laps of the loop execution.

When the first time loop executes the value of counter is initialized 0. Then it will check the boolean expression that is “counter < 10” or “0 < 10” that will return true. That means the loop can be executed. Than the loop starts the execution of the code inside its body ( printing the value of counter). At last the third argument expression (counter increment) executes (increasing the value of counter to 1, that is the value of counter is now 1). Now loop restart the process but now the initialization does not execute. It will check the Boolean expression that is now “counter < 10” = “1 < 10” that will return true. The process continues until the Boolean expression results to false (when the counter’s value reaches greater than or equals to 10). Because “10 < 10” will result to false.

Step 1:                  Execute the initialization code.
Step 2:                  Check the Boolean expression. If it is true then go to Step 3. Otherwise go to Step 6:
Step 3:                  Execute the code inside the loops body.
Step 4:                  Execute the Increment/Decrement expression.
Step 5:                  Go to Step 2.
Step 6:                  Loop Ends.

      
Delegate Command in VB.NET

Delegate Command in VB.NET

Following code snippet contains the implementation of ICommand interface. The code below shows a generic implementation of ICommand interface.


Code:

Namespace Commands
    Public Class DelegateCommand(Of T)
        Implements ICommand
 
        Private executeMethod As Action(Of T)
        Private canExecuteMethod As Func(Of T, Boolean)
 
        ''' 
        ''' Occurs when changes occur that affect whether or not the command should execute.
        ''' 
        ''' 
        Public Event CanExecuteChanged As EventHandler Implements System.Windows.Input.ICommand.CanExecuteChanged
 
        ''' 
        ''' Initializes a new instance of  class.
        ''' 
        ''' Method that execute when command is invoked.
        Public Sub New(ByVal executeMethod As Action(Of T))
            MyClass.New(executeMethod, Nothing)
        End Sub
 
        ''' 
        ''' Initializes a new instance of  class.
        ''' 
        ''' Method that execute when command is invoked.
        ''' Method that determines whether the command can execute in its current state.
        Public Sub New(ByVal executeMethod As Action(Of T), ByVal canExecuteMethod As Func(Of T, Boolean))
            If executeMethod Is Nothing AndAlso canExecuteMethod Is Nothing Then
                Throw New ArgumentNullException("executeMethod")
            End If
            Me.executeMethod = executeMethod
            Me.canExecuteMethod = canExecuteMethod
        End Sub
 
        ''' 
        '''  Determines whether the command can execute in its current state.
        ''' 
        ''' Data used by the command. If the command does not require data to be passed, this object can be set to null.
        ''' True if this command can be executed; otherwise, False.
        Public Function CanExecute(ByVal parameter As Object) As Boolean Implements System.Windows.Input.ICommand.CanExecute
            If canExecuteMethod Is Nothing Then
                Return True
            End If
            If parameter Is Nothing Then
                Return canExecuteMethod(Nothing)
            End If
            Return canExecuteMethod(CType(parameter, T))
        End Function
 
        ''' 
        ''' Called when the command is invoked.
        ''' 
        ''' Data used by the command. If the command does not require data to be passed, this object can be set to null.
        Public Sub Execute(ByVal parameter As Object) Implements System.Windows.Input.ICommand.Execute
            If executeMethod Is Nothing Then
                Return
            End If
            If parameter Is Nothing Then
                executeMethod(Nothing)
            Else
                executeMethod(CType(parameter, T))
            End If
        End Sub
 
        ''' 
        ''' Raises the CanExecuteChanged event.
        ''' 
        Public Sub RaiseCanExecuteChanged()
            RaiseEvent CanExecuteChanged()
        End Sub

    End Class
End Namespace

Creating Generic DropDown Control in WPF (Updated)

Creating Generic DropDown Control in WPF (Updated)


Following code snippet update to my previous code snippet. In this code snippet now I have added XML doc comments and CustomPopupPlacementCallback implementation.

Imports System.Windows.Controls.Primitives
Imports System.ComponentModel
 
''' <summary>
''' A drop-down control control. Drop-down can be shown by clicking on the control.
''' </summary>
Public Class DropDownControl
    Inherits System.Windows.Controls.Primitives.ToggleButton
 
    ''' <summary>
    ''' Initializes shared resources of <see cref="DropDownControl"/> class.
    ''' </summary>
    Shared Sub New()
        'This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class.
        'This style is defined in themes\generic.xaml
        DefaultStyleKeyProperty.OverrideMetadata(GetType(DropDownControl), New FrameworkPropertyMetadata(GetType(DropDownControl)))
    End Sub
 
    ''' <summary>
    ''' Initializes a new instance of <see cref="DropDownControl"/> class.
    ''' </summary>
    Public Sub New()
        Popup = New Popup()
        Popup.StaysOpen = False
        Popup.Placement = PlacementMode.Custom
        Popup.AllowsTransparency = True
        Me.SetBinding(IsCheckedProperty, "Popup.IsOpen")
    End Sub
 
    ''' <summary>
    ''' Gets or sets the Popup element.
    ''' </summary>
    Public Property Popup As Popup
        Get
            Return GetValue(PopupProperty)
        End Get
        Set(ByVal value As Popup)
            SetValue(PopupProperty, value)
        End Set
    End Property
 
    ''' <summary>
    ''' Identifies the <see cref="Popup"/> dependency property.
    ''' </summary>
    Public Shared ReadOnly PopupProperty As DependencyProperty = _
                           DependencyProperty.Register("Popup", _
                           GetType(Popup), GetType(DropDownControl), _
                           New FrameworkPropertyMetadata(NothingNew PropertyChangedCallback(AddressOf OnPopupChanged)))
 
    ''' <summary>
    ''' Gets or sets the Drop-down element.
    ''' </summary>
    Public Property DropDown As FrameworkElement
        Get
            Return GetValue(DropDownProperty)
        End Get
        Set(ByVal value As FrameworkElement)
            SetValue(DropDownProperty, value)
        End Set
    End Property
 
    ''' <summary>
    ''' Identifies the <see cref="DropDown"/> dependency property.
    ''' </summary>
    ''' <remarks></remarks>
    Public Shared ReadOnly DropDownProperty As DependencyProperty = _
                           DependencyProperty.Register("DropDown", _
                           GetType(FrameworkElement), GetType(DropDownControl), _
                           New FrameworkPropertyMetadata(NothingNew PropertyChangedCallback(AddressOf OnDropDownChanged)))
 
    ''' <summary>
    ''' Represents the callback that is invoked when the value of <see cref="DropDown"/> dependency property changes.
    ''' </summary>
    ''' <param name="d">The <see cref="DropDownControl"/> on which the property has changed value.</param>
    ''' <param name="e">Event data that is issued by any event that tracks changes to the effective value of this property.</param>
    ''' <remarks></remarks>
    Private Shared Sub OnDropDownChanged(ByVal d As System.Windows.DependencyObjectByVal e As System.Windows.DependencyPropertyChangedEventArgs)
        Dim ddc As DropDownControl = d
        If ddc.Popup IsNot Nothing Then
            ddc.Popup.Child = e.NewValue
        End If
    End Sub
 
    ''' <summary>
    ''' Represents the callback that is invoked when the value of <see cref="DropDown"/> dependency property changes.
    ''' </summary>
    ''' <param name="d">The <see cref="DropDownControl"/> on which the property has changed value.</param>
    ''' <param name="e">Event data that is issued by any event that tracks changes to the effective value of this property.</param>
    ''' <remarks></remarks>
    Private Shared Sub OnPopupChanged(ByVal d As System.Windows.DependencyObjectByVal e As System.Windows.DependencyPropertyChangedEventArgs)
        Dim dropdown As DropDownControl = d
        Dim popup As Popup = e.NewValue
        Dim oldPopup As Popup = e.OldValue
        If oldPopup IsNot Nothing Then
            popup.CustomPopupPlacementCallback = Nothing
        End If
        If popup IsNot Nothing Then
            popup.CustomPopupPlacementCallback = New CustomPopupPlacementCallback(AddressOf dropdown.GetCustomPoupPlacement)
        End If
    End Sub
 
    ''' <summary>
    ''' Represents a method that provides custom positioning for a Popup control.
    ''' </summary>
    ''' <param name="popupSize">The System.Windows.Size of the System.Windows.Controls.Primitives.Popup control.</param>
    ''' <param name="targetSize">The System.Windows.Size of the System.Windows.Controls.Primitives.Popup.PlacementTarget.</param>
    ''' <param name="offset">The System.Windows.Point computed from the System.Windows.Controls.Primitives.Popup.HorizontalOffset and System.Windows.Controls.Primitives.Popup.VerticalOffset property values.</param>
    Private Function GetCustomPoupPlacement(ByVal popupSize As System.Windows.SizeByVal targetSize As System.Windows.SizeByVal offset As System.Windows.PointAs CustomPopupPlacement()
        Dim sPoint As Point = Me.PointToScreen(New Point(0, 0))
        Dim tX As Double = 0
        Dim tY As Double = targetSize.Height
 
        If popupSize.Width + sPoint.X > SystemParameters.PrimaryScreenWidth Then
            tX = -(popupSize.Width - targetSize.Width)
        End If
        If popupSize.Height + sPoint.Y > SystemParameters.PrimaryScreenHeight Then
            tY = -popupSize.Height
        End If
 
        Return New CustomPopupPlacement() {New CustomPopupPlacement(New Point(tX, tY), PopupPrimaryAxis.Horizontal)}
    End Function
 
    ''' <summary>
    ''' Called when a control is clicked by the mouse or the keyboard.
    ''' </summary>
    Protected Overrides Sub OnClick()
        MyBase.OnClick()
        Popup.PlacementTarget = Me
        Popup.IsOpen = True
    End Sub
 
End Class
Creating Generic DropDown Control in WPF

Creating Generic DropDown Control in WPF

Following code snippet shows how to create a custom DropDown control in WPF.


Imports System.Windows.Controls.Primitives
Imports System.ComponentModel
 
Public Class DropDownControl
    Inherits System.Windows.Controls.Primitives.ToggleButton
 
    Shared Sub New()
        'This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class.
        'This style is defined in themes\generic.xaml
        DefaultStyleKeyProperty.OverrideMetadata(GetType(DropDownControl), New FrameworkPropertyMetadata(GetType(DropDownControl)))
    End Sub
 
    Public Sub New()
        Popup = New Popup()
        Popup.StaysOpen = False
        Me.SetBinding(IsCheckedProperty, "Popup.IsOpen")
    End Sub
 
    Public Property Popup As Popup
        Get
            Return GetValue(PopupProperty)
        End Get
 
        Set(ByVal value As Popup)
            SetValue(PopupProperty, value)
        End Set
    End Property
 
    Public Shared ReadOnly PopupProperty As DependencyProperty = _
                           DependencyProperty.Register("Popup", _
                           GetType(Popup), GetType(DropDownControl), _
                           New FrameworkPropertyMetadata(Nothing))
 
    Public Property DropDown As FrameworkElement
        Get
            Return GetValue(DropDownProperty)
        End Get
 
        Set(ByVal value As FrameworkElement)
            SetValue(DropDownProperty, value)
        End Set
    End Property
 
    Public Shared ReadOnly DropDownProperty As DependencyProperty = _
                           DependencyProperty.Register("DropDown", _
                           GetType(FrameworkElement), GetType(DropDownControl), _
                           New FrameworkPropertyMetadata(NothingNew PropertyChangedCallback(AddressOf OnDropDownChanged)))
 
    Private Shared Sub OnDropDownChanged(ByVal d As System.Windows.DependencyObjectByVal e As System.Windows.DependencyPropertyChangedEventArgs)
        Dim ddc As DropDownControl = d
        If ddc.Popup IsNot Nothing Then
            ddc.Popup.Child = e.NewValue
        End If
    End Sub
 
    Protected Overrides Sub OnClick()
        MyBase.OnClick()
        Popup.PlacementTarget = Me
        Popup.Placement = PlacementMode.Bottom
        Popup.IsOpen = True
    End Sub
 
End Class

Kategori

Kategori