Showing posts with label MVVM. Show all posts
Showing posts with label MVVM. Show all posts

Monday, April 16, 2012

Creating Cut, Copy, Paste Context menu for all textboxs in silverlight using Style in App.xaml

This article will provide you the help for creating Cut, Copy, Paste Context menu for all textboxs in silverlight using Style in App.xaml. This style will work for every Textbox that you will add in any form of your application..

App.xaml


xmlns:my="clr-namespace:YourApplicationNameSpace"



<Application.Resources>
  <Style TargetType="TextBox">
     <Setter Property="my:ControlCustomBehaviors.SetMenu" Value="true" />
  Style>
Application.Resources>

ControlCustomBehaviors.cs

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;


namespace YourApplicationNameSpace
{

public class ControlCustomBehaviors : Behavior<Control>
{

#region Set Context Menu
public static DependencyProperty SetMenuProperty =
          DependencyProperty.RegisterAttached("SetMenu",
                                              typeof(object),
                                              typeof(ControlCustomBehaviors),                                            new PropertyMetadata(null, SetMenuProp));
       
private static TextBox tBox;
private static void SetMenuProp(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
 tBox = d as TextBox;
 CreateMenu();


 tBox.MouseRightButtonDown += new    MouseButtonEventHandler(AssociatedObject_MouseRightButtonDown);

 tBox.MouseRightButtonUp += new MouseButtonEventHandler(AssociatedObject_MouseRightButtonUp);

 tBox.SetValue(ContextMenuService.ContextMenuProperty, _contextMenu);

}

public static object GetSetMenu(UIElement obj)
{
    return (object)obj.GetValue(SetMenuProperty);
}
public static void SetSetMenu(DependencyObject obj, object txtbox)
{
     obj.SetValue(SetMenuProperty, txtbox);
}

private static ContextMenu _contextMenu;
private static MenuItem _copy;
private static MenuItem _cut;
private static MenuItem _paste;

private static void CreateMenu()
{
  _contextMenu = new ContextMenu();
  _cut = new MenuItem();
  _cut.Header = "Cut";
  _cut.Click += new RoutedEventHandler(cut_Click);
  _contextMenu.Items.Add(_cut);

  _copy = new MenuItem();
  _copy.Header = "Copy";
  _copy.Click += new RoutedEventHandler(copy_Click);
  _contextMenu.Items.Add(_copy);

   _paste = new MenuItem();
   _paste.Header = "Paste";
   _paste.Click += new RoutedEventHandler(paste_Click);
   _contextMenu.Items.Add(_paste);
  }
  static void paste_Click(object sen, RoutedEventArgs e)
  {
    tBox.SelectedText = Clipboard.GetText();
    _contextMenu.IsOpen = false;
     tBox.Focus();
  }
  static void cut_Click(object sen, RoutedEventArgs e)
  {
     Clipboard.SetText(tBox.SelectedText);
     tBox.SelectedText = string.Empty;
     _contextMenu.IsOpen = false;
     tBox.Focus();
  }
  static void copy_Click(object sen, RoutedEventArgs e)
  {
      Clipboard.SetText(tBox.SelectedText);
      _contextMenu.IsOpen = false;
      tBox.Focus();
  }

  static void AssociatedObject_MouseRightButtonUp(object Sender,  MouseButtonEventArgs e)
        {
  if (Clipboard.ContainsText() && tBox.IsReadOnly == false && tBox.IsEnabled == true)
  {
     _paste.IsEnabled = true;
  }
  else
  {
   _paste.IsEnabled = false;
  }
  if (string.IsNullOrEmpty(tBox.SelectedText))
  {
    _cut.IsEnabled = false;
    _copy.IsEnabled = false;
  }
  else
  {
    _cut.IsEnabled = true;
    _copy.IsEnabled = true;
  }
  _contextMenu.IsOpen = true;
   tBox.Focus();

  }
  static void AssociatedObject_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
 {
    tBox = sender as TextBox;
    e.Handled = true;
 }
 #endregion

}
}

Wednesday, February 15, 2012

Handling Text box for only positive Integers No and showing error message in silverlight Using MVVM

Following is the property that can be bind to text box, and handles the text box to enter only integer values, and converting to positive Integer value if any negative Integer value will entered in text box.



private String strPageSize = "";

public String PageSize
{
 get { return strPageSize; 
 set
    {

     Regex myRange = new Regex(@"^-{0,1}\d+$");
     if (!myRange.IsMatch(value))
     {
       throw new Exception("Numbers are allowed only");
     }
     strPageSize = (Math.Abs(Convert.ToDecimal(value))).ToString();
     RaisePropertyChanged("PageSize");
     }
}

Wednesday, January 25, 2012

Handling Button Click Event in ViewModel using MVVM structure of Silverlight

1. Write Xaml as follows
<Button Command="{Binding SearchCommand}" Content="Search" 
Height="20" HorizontalAlignment="Right" 
Margin="0,16,19,0" TabIndex="14" VerticalAlignment="Top" 
Width="75" Grid.Column="2" />
2. Write in viewModel as follows
//This is command against when search button will be pressed
 public RelayCommand SearchCommand
 {
    get
    {
      //GetDatais a method for your action on click event
      return new RelayCommand(GetData);
    }
 }
3. You Method for for on button click
protected void GetData()
{
     //Your work
     //
     //
}

Tuesday, January 24, 2012

Using Busy indicator of Master Page from the Child Page in MVVM structure of Silver light

You can call the busy indicator of silver light master page from the child form in the following way..

1. Register the Message in constructor of MasterPage View Model

public vmMasterPage()
{
   //Your other work
   Messenger.Default.Register(this, "GetBusy", getBusy);
}

2. Define the function in MasterPage view Model
public void getBusy(string msg)
        {
            //MainPageBusyIndicator is bool property to bind with busyindcator control on masterPage
            //
            if (msg == "Busy")
            {
                MainPageBusyIndicator = true;
            }
            else
            {
                MainPageBusyIndicator = false; 
            }
        }

3. Call This Message from your Child form as follows
Messenger.Default.Send("Busy", "GetBusy");



Thursday, January 19, 2012

Using Messanger for calling View method from ViewModel in MVVM structure of Silver light

Write in View Constructor

Messenger.Default.Register(this, "DoFocus", doFocus);

Write method in view that need to be call from view model
public void doFocus(string msg)
        {
            if (msg == "focus")
            {
                System.Windows.Browser.HtmlPage.Plugin.Focus();
                this.txtSalesOrderNo.Focus();
            }
        }

Now you can call the above method from viewmodel as below

Messenger.Default.Send("focus", "DoFocus");

How to set textbox focus in silverlight using MVVM

The question has been asked a couple of times, unfortunately the answers only apply to WPF. Anyone know how to accomplish this in silverlight? Basically I need to focus on a certain textbox from code.

Following class is required in view model

public class FocusBehavior : Behavior
    {

        protected override void OnAttached()
        {
            AssociatedObject.GotFocus += (sender, args) => IsFocused = true;
            AssociatedObject.LostFocus += (sender, a) => IsFocused = false;
            AssociatedObject.Loaded += (o, a) => { if (HasInitialFocus || IsFocused) AssociatedObject.Focus(); };

            base.OnAttached();
        }

        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.Register(
                "IsFocused",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, (d, e) => { if ((bool)e.NewValue) ((FocusBehavior)d).AssociatedObject.Focus(); }));

        public bool IsFocused
        {
            get { return (bool)GetValue(IsFocusedProperty); }
            set { SetValue(IsFocusedProperty, value); }
        }

        public static readonly DependencyProperty HasInitialFocusProperty =
            DependencyProperty.Register(
                "HasInitialFocus",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, null));

        public bool HasInitialFocus
        {
            get { return (bool)GetValue(HasInitialFocusProperty); }
            set { SetValue(HasInitialFocusProperty, value); }
        }
    }

Add name space reference in Xaml file like as
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 

and give initial value and binding value like as below
 <TextBlock Height="20" HorizontalAlignment="Left" Margin="10,16,0,0" Text="Sales Order No" TextWrapping="Wrap" VerticalAlignment="Top" Width="91" />
        <TextBox Height="22"  HorizontalAlignment="Left" Margin="115,13,0,0" MaxLength="20" Name="txtSalesOrderNo" TabIndex="0"  TextWrapping="Wrap" VerticalAlignment="Top" Width="165" Text="{Binding Path=SaleOrderNo, Mode=TwoWay}" >
            <i:Interaction.Behaviors>
                <Local1:FocusBehavior HasInitialFocus="False" IsFocused="{Binding SaleOrderFocus, Mode=TwoWay}"/>
            </i:Interaction.Behaviors>


        </TextBox>