RecentComments

Comment RSS

Autosuggest Textbox for WPF

by Ioannis 1. July 2010 19:57

Here is an implementation of a nice Textbox in WPF that suggests possible values based on the current user’s input. It is different from WPF’s native editable Combobox since it does not load all possible values at initialization (saving time and memory). The Textbox calls a method that returns the suggested values as soon as it detects a specific amount of idle time in the user’s typing. This method will probably access the database using the value entered so far in the Textbox as the criterion for the suggested values.

The main idea is as follows:

We create a grid whose first row contains a textbox and the second row contains a Listbox. Now, when the textbox gets the focus and its text changes due to the user’s input, between the user’s key presses we start a countdown timer. If the timer reaches zero before the user pressing another button, we call a method to retrieve the suggested values and display the textbox with those values. Now, if the user selects one of them, then we fill the textbox with the appropriate selection.

The TTimer.cs file contains the TTimer class that creates a primitive countdown timer:

public class TTimer
    {
        private Timer timer;
        public event Action<int> DoSomething;
        private int _timesCalled = 0;
 
        public TTimer()
        { }
        public void Start(int PeriodInSeconds)
        {
            timer = new System.Threading.Timer(timer_Task, null, 0,
            PeriodInSeconds * 1000);
        }
        public void Stop()
        {
            if (timer!=null)
            timer.Dispose();
        }
        private void timer_Task(object State)
        {
            _timesCalled++;
            DoSomething(_timesCalled);
        }
    }

The Autosuggest Textbox is implemented in AutoSuggestTextBox.xaml(.cs) and it is called TextBoxAS. Its properties are:

IdleTime: Defines the time to wait for the ListBox to appear when the user is idle.

ListHeight: Is the height of the Listbox with the suggested values.

ValueMember: Is the property of the objects in the list that should appear in the Textbox if the object is selected (.ToString() is used if empty).

DisplayMember: The property of the objects in the list that is displayed in the list (.ToString() is used if empty).

SelectedValue: Is the selected value from the ListBox.

The rest of the implementation is catching events and responding accordingly. The main action behind the events are summarized in the following list:

 

  • TextBox – TextChanged: When the text of the Textbox is changed if the Listbox is visible (_suggestingIsActive is true) we hide it since a new cycle should begin otherwise (_suggestingIsActive=false) we reset the countdown.
  • ListBox – SelectionChnaged: When the user has selected something from the ListBox we set this value to the SelectedValue dependency property.
  • TextBox-LostKeyboradFocus: When the TextBox loses the focus it is either because the user clicked on a value in the ListBox or because the user has navigated away to another control. If the first is true then if the SelectedValue DP has something, we use it to set the value of the TextBox. If the second is true we try to see whether the value entered in the TextBox can help us set the SelectedValue (there is only one suggestion for the value). Otherwise we revert to the previous value.
  • TextBox-GotKeyboradFocus: Initializes the timer.

 

The TextBox defines the event OnGetSuggestions that can be used to set the method to be called when the control needs to get the suggestions for a specific text.

Typical usage of the control is as follows:

<Controls:TextBoxAS Name="ASTextBox" 
                    Width="233" Height="171" Canvas.Left="28" Canvas.Top="25"  
                    OnGetSuggestions="TextBoxAS_OnGetSuggestions" 
                    DisplayMember="FullDescription" ValueMember="Name" 
                    ListHeight="150" />

In order to allow the ListBox to open on top of other controls, those controls should be defined in xaml before the definition of the TextBox.

You can download the sources for the project here

Shout it

Going from Model-View-Presenter to MV-VM with WPF Commands (Part #3: MVVM and Commands)

by Ioannis 12. October 2009 07:44

In previous posts (Part 1 and Part2) I have presented the implementation of a toy application using the Model-View-Presenter pattern and Routed Commands. In this final post, I will present the migration to MVVM. In Part2, we have reached a point where we have managed to partly centralize the logic that is needed to be implemented for each Command but we were not yet fully satisfied with the wiring that needed to be done in the code-behind file. So, we will try to tackle this problem:

Approach #4 Our first ViewModel for MVVM

Our first ViewModel is an implementation that looks a lot like the presenter. The code is as follows:

    public class ViewModel
    {
        private Client _selectedClient = null;
        public Client SelectedClient
        {
            get { return _selectedClient; }
            set { _selectedClient = value; }
        }
        public ObservableCollection<Client> Clients
        {
            get { return ClientRepository.GetClients(); }
        }
        public void AddClientCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ClientRepository.AddClient(new Client());
        }
        public void AddClientCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
        public void DeleteClientCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_selectedClient != null)
            {
                ClientRepository.DeleteClient(_selectedClient);
            }
        }
        public void DeleteClientCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = (_selectedClient != null);
        }
        public void ResetClientCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_selectedClient != null)
            {
                _selectedClient.FirstName = "RESET";
                _selectedClient.LastName = "RESET";
                _selectedClient.Phone = "9999999999";
            }
        }
        public void ResetClientCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = (_selectedClient != null);
        }
    }

The whole idea behind the MVVM model is the use of a ViewModel class that will provide everything needed to the View through the use of Bindings. Therefore, we want to have a code-behind file that contains the following:

public partial class Window4 : Window
{
    ViewModel model = new ViewModel();

    public Window4()
    {
        InitializeComponent();

        this.DataContext = model;

        this.CommandBindings.Add(new CommandBinding(ClientCommands.AddClient, 
                    model.AddClientCommand_Executed, model.AddClientCommand_CanExecute));
        this.CommandBindings.Add(new CommandBinding(ClientCommands.DeleteClient, 
                    model.DeleteClientCommand_Executed, model.DeleteClientCommand_CanExecute));
        this.CommandBindings.Add(new CommandBinding(ClientCommands.ResetClient, 
                    model.ResetClientCommand_Executed, model.ResetClientCommand_CanExecute));
       
    }
}

That is we initialize the ViewModel, we set the Window's DataContext to the model and associate the commands with methods of the ViewModel. The xaml file is similar to the previous approach but it does not define the Command bindings (since they are defined in code)  and the handler for the ListBox SelectionChanged event is substituted with a binding of the SelectedItem property to the SelectedClient property of the ViewModel.

Are we finished? Not quite so. Although we have managed to take most of the code out of the code-behind file, achieving a separation between GUI and logic, there are still the binding definitions that need to be specified in every window that uses Commands. We would really like to avoid writing those as well. That leads us to:

Approach #5 The final MVVM model

Up to this point we have been working with Routed Commands. As previously stated, Routed Commands are fired from controls and bubble up the visual tree until they find a control that holds the binding that implements their logic. What we want to do to the view is the following. We want to avoid defining the Command Bindings and assocate the MenuItems with something like this:

 

<MenuItem x:Name="MenuItemAddClient"  Header="{Binding Path=AddClientText}" 
          Command="{Binding Path=AddClient}" />
<MenuItem x:Name="MenuItemDeleteClient" Header="{Binding Path=DeleteClientText}" 
          Command="{Binding Path=DeleteClient}" />
<MenuItem x:Name="MenuItemEditClient" Header="{Binding Path=ResetClientText}" 
          Command="{Binding Path=ResetClient}" />

That is, we bind the command's implemementaion to the MenuItems directly in the xaml file. There is no routing of the commands to other visual elements.

For this approach to work we need to make the AddClient, DeleteClient and ResetClient commands implement the ICommand interface. Or, because all commands will share some functionaliy in common, we can create the following class that implements the ICommand interface and delegates the behavior according to the command:

public class SimpleCommand:ICommand
    {
        public Predicate<object> CanExecuteDelegate { get; set; }
        public Action<object> ExecuteDelegate { get; set; }

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            if (CanExecuteDelegate!=null) return CanExecuteDelegate(parameter);
            return true;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            if (ExecuteDelegate!=null) ExecuteDelegate(parameter);
        }

        #endregion
    }

The new ViewModel is as follows. Note the implementation of the commands compared to the previous version, where each command defines its own delegate methods that implements its logic.

 

    public class ViewModel2
    {
        private Client _selectedClient = null;
        public Client SelectedClient
        {
            get { return _selectedClient; }
            set { _selectedClient = value; }
        }

        public ObservableCollection<Client> Clients
        {
            get { return ClientRepository.GetClients(); }
        }

        private string _addClientText="Add Client";
        public string AddClientText
        {
            get { return _addClientText; }
            set { _addClientText = value; }
        }

        private string _deleteClientText="Delete Client";
        public string DeleteClientText
        {
            get { return _deleteClientText; }
            set { _deleteClientText = value; }
        }

        private string _resetClientText="Reset Client";
        public string ResetClientText
        {
            get { return _resetClientText; }
            set { _resetClientText = value; }
        }

        private SimpleCommand _addClient = new SimpleCommand();

        public SimpleCommand AddClient
        {
            get { return _addClient; }
            set { _addClient = value; }
        }

        private SimpleCommand _resetClient = new SimpleCommand();

        public SimpleCommand ResetClient
        {
            get { return _resetClient; }
            set { _resetClient = value; }
        }
        private SimpleCommand _deleteClient = new SimpleCommand();

        public SimpleCommand DeleteClient
        {
            get { return _deleteClient; }
            set { _deleteClient = value; }
        }

        public ViewModel2()
        {
            AddClient.CanExecuteDelegate += new Predicate<object>(AddClientCommand_CanExecute);
            AddClient.ExecuteDelegate += new Action<object>(AddClientCommand_Executed);

            ResetClient.CanExecuteDelegate += new Predicate<object>(ResetClientCommand_CanExecute);
            ResetClient.ExecuteDelegate += new Action<object>(ResetClientCommand_Executed);

            DeleteClient.CanExecuteDelegate += new Predicate<object>(DeleteClientCommand_CanExecute);
            DeleteClient.ExecuteDelegate += new Action<object>(DeleteClientCommand_Executed);
        }
        public void AddClientCommand_Executed(object sender)
        {
            ClientRepository.AddClient(new Client());
        }
        public bool AddClientCommand_CanExecute(object sender)
        {
            return true;
        }
        public void DeleteClientCommand_Executed(object sender)
        {
            if (_selectedClient != null)
            {
                ClientRepository.DeleteClient(_selectedClient);
            }
        }
        public bool DeleteClientCommand_CanExecute(object sender)
        {
            return (_selectedClient != null);
        }
        public void ResetClientCommand_Executed(object sender)
        {
            if (_selectedClient != null)
            {
                _selectedClient.FirstName = "RESET";
                _selectedClient.LastName = "RESET";
                _selectedClient.Phone = "9999999999";
            }
        }
        public bool ResetClientCommand_CanExecute(object sender)
        {
            return (_selectedClient != null);
        }
    }

 And that is all. The code-behind file now is as simple as this:

    public partial class Window5 : Window
    {
        ViewModel2 model = new ViewModel2();

        public Window5()
        {
            InitializeComponent();
            this.DataContext = model;          
        }
    }

and all the wiring is performed in the ViewModel. This is the maximum separation achieved with the MVVM pattern.

The project with all the approaches can be downloaded here.

 kick it on DotNetKicks.comShout it

Tags:

WPF

Going from Model-View-Presenter to MV-VM with WPF Commands (Part #2: Commands with MVP)

by Ioannis 12. October 2009 07:25

In my previous post, I have presented the first two approaches for implementing the GUI and the logic of a toy application:

 

  • Approach #1: All the logic in the code behind file.
  • Approach #2: The Model-View-Presenter pattern.

 

In this post, we will pick up from where we stopped, in our route to migrate to the benefits of the MVVM model and the use of Commands. It is recommended to take a look at the previous post in order to get an idea of the application and the two previous approaches)

 

Approach #3: A hybrid MVP that uses Routed Commands (Seeing the first benefits)

In this approach we will keep the MVP pattern but we will try to substitute the MenuItems' event handlers with Routed Commands. For a Routed Command to work, we need a place to define it, a control that fires the command and a control that will implement the logic that needs to be performed. They are called Routed because in the visual tree, the command will bubble up from the control that fired it to the control that carries the binding that implement its logic.

In our small scale application, we will need 3 Commands which are defined in a separate Command.cs file as follows:

public class ClientCommands
{
    private static RoutedUICommand addClient;
    private static RoutedUICommand resetClient;
    private static RoutedUICommand deleteClient;

    static ClientCommands()
    {
        InputGestureCollection inputs = new InputGestureCollection();
        inputs.Add(new KeyGesture(Key.N, ModifierKeys.Control, "Ctrl+N"));
        addClient = new RoutedUICommand("Add Client", "AddClient", typeof(ClientCommands), inputs);

        inputs = new InputGestureCollection();
        inputs.Add(new KeyGesture(Key.R, ModifierKeys.Control, "Ctrl+R"));
        resetClient = new RoutedUICommand("Reset Client", "ResetClient", typeof(ClientCommands), inputs);

        inputs = new InputGestureCollection();
        inputs.Add(new KeyGesture(Key.D, ModifierKeys.Control, "Ctrl+D"));
        deleteClient = new RoutedUICommand("Delete Client", "DeleteClient", typeof(ClientCommands), inputs);
    }

    public static RoutedUICommand AddClient
    {
        get { return addClient; }
    }
    public static RoutedUICommand DeleteClient
    {
        get { return deleteClient; }
    }
    public static RoutedUICommand ResetClient
    {
        get { return resetClient; }
    }
}

Note that three commands are defined for the Add Client, Delete Client and Reset Client actions of the MenuItems. The Commands are bound to specific key shortcuts (this is global - a nice benefit out of the box with Commands) and in their constructors provide the text that will appear in the Buttons or MenuItems that will fire them. For example, the MenuItem that will fire the Command AddClient and all other future Buttons that will fire the same Command, will display with no extra effort the text "Add Client" (a second benefit with Commands where you have a centralized way of defining the language of the text of the controls- great for localization).

Having defined the commands we need to alter the xaml file for using them in the View. This is done as follows. First we define that the Commands are fired from the MenuItems (in the place where the event handler definitions used to be):

 

<MenuItem Header="{Binding RelativeSource={RelativeSource Self},Path=Command.Text}" 
     Command="local:ClientCommands.AddClient" />
<MenuItem Header="{Binding RelativeSource={RelativeSource Self},Path=Command.Text}" 
     Command="local:ClientCommands.DeleteClient"/>
<MenuItem Header="{Binding RelativeSource={RelativeSource Self},Path=Command.Text}" 
     Command="local:ClientCommands.ResetClient"/>
 

Do not forget to reference the namespace the ClientCommands class resides at the beginning of the xaml file as "local". Then, we need to specify the place Routed Commands are caught to be handled. We choose that place to be the Window itself. Therefore the command bindings are defined in the Window as follows:

 

<Window.CommandBindings>
    <CommandBinding Command="local:ClientCommands.AddClient" 
	Executed="AddClientCommand_Executed" CanExecute="AddClientCommand_CanExecute"/>
    <CommandBinding Command="local:ClientCommands.DeleteClient" 
	Executed="DeleteClientCommand_Executed" CanExecute="DeleteClientCommand_CanExecute"/>
    <CommandBinding Command="local:ClientCommands.ResetClient" 
	Executed="ResetClientCommand_Executed"  CanExecute="ResetClientCommand_CanExecute"/>
</Window.CommandBindings>

 

For the Commands, we define two handlers. The one is the Executed method which holds the implementation of the logic of each command. The other is the CanExecute method which is called by the GUI in order to determine whether the control which fires the command should be enabled or not. Note that implementing this method will provide a disable/enable mechansim to all the Controls the fire the command with no additional effort.

The logic in the code-behind file, is similar to the previous case with the difference that now instead of event handles we have Routed Event handlers:

    public partial class Window3 : Window,IView
    {
        IPresenter myPresenter = new Presenter();
        public Window3()
        {
            myPresenter.SetView(this);
            InitializeComponent();
            myPresenter.InitGUI();
        }
        private void ListBoxClients_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            myPresenter.SetSelectedClient(ListBoxClients.SelectedItem as Client);
        }

        #region IView Members

        public void ToggleMenuItems(bool Enable)
        {
            this.MenuItemEditClient.IsEnabled =Enable;
            this.MenuItemDeleteClient.IsEnabled = Enable;
        }
        public void InitializeList(ObservableCollection<Client> Clients)
        {
            this.ListBoxClients.ItemsSource = Clients;
        }

        #endregion

        private void AddClientCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            myPresenter.AddClient();
        }
        private void AddClientCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
        private void DeleteClientCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            myPresenter.DeleteClient();
        }
        private void DeleteClientCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = myPresenter.EditAddCanExecute();
        }
        private void ResetClientCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            myPresenter.ResetClient();
        }
        private void ResetClientCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = myPresenter.EditAddCanExecute();
        }
    }

 We need to add in the Presenter class the method EdtAddCanExecute which determines when the commands need to be fired. Let's summarize what we have achieved s far:

 

  • We have enabled easy testing for our application with the MVP pattern (previous post).
  • We have enabled easy change of the View or the logic of the Presenter through the use of interfaces.
  • We have centralized the key shortcuts and the dispayed text of the commands in our application.
  • We have provided a specific method that defines for all controls that fire the command, whether they should be enabled or not

 

But we still have some problems. First there is still a lot of wiring up that needs to be done in the code behind file. Second, commands are implemented in the code-behind file (although they divert the execution to the presenter). Consider that it is problematic to implement the CanExecute wiring in every Window that fires the command.

In the next and final post on this series we will fully implement the MVVM model which also solves the aforementioned issues.

kick it on DotNetKicks.com Shout it

Tags:

WPF

Powered by BlogEngine.NET 1.5.0.7

Programming Blogs - BlogCatalog Blog Directory Add to Technorati Favorites

MVP Award

Ioannis Panagopoulos





This blog is using BlogEngine.Net and is hosted in the hoster below. I have not experienced any problems installing BlogEngine.Net in the host and I am satisfied with the host's response times. Therefore I recommend it.


DiscountASP Add