Monthly Archives: June 2015

Adding a snippet in Visual Studio

Adding a snippet in Visual Studio can save time later..

Open notepad and type:



    
        
Hello World C# Myself Says Hello to the world. hello
System.Windows.Forms.dll System.Windows.Forms

Place your code after :


Save as utf-8!

Copy to: C:\Users\\Documents\Visual Studio \Code Snippets\Visual C#\My Code Snippets\.snippet

See: https://msdn.microsoft.com/en-us/library/ms165394.aspx

My Snippet to set up a viewmodel for my project:



    
        
ViewModel geoffviewmodel Geoff Atkinson Create Basic ViewModel Layout
ViewModelName Name of this View Model MyViewModel

Datagrid row delete button with new row placeholder disable

Aim:

To create a button on a datagrid to delete a row but not crash on the new row placeholder row.

Method:

Add a column like any other inside the datagrid but use a template type to show the button.

                        
                            
                                
                            
                        
                    

Add a converter to check for the new row place holder:

    [ValueConversion(typeof(string), typeof(Boolean))]
    public class PlaceHolderConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.ToString() == "{DataGrid.NewItemPlaceholder}")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new Exception();
        }
    }

WPF Commands

First Create a Delegate in ViewModel as a declaration:

public DelegateCommand Deploy { get; set; } 

Next create the method you are going to call:

//Deploy Module Clicked - This one takes ro_clientmodules_extend from my grid!
private void Deploy_click(ro_clientmodules_extend obj)
{

}

Next sort out the viewmodel constructor:

public LicenseDeploymentModuleViewModel()
{
   Deploy = new DelegateCommand(Deploy_click);
}

Finally deal with the XAML:

Note: Mine is inside the Datagrid as a button on a row. Yours may need adjusting to tweek the relative path!
Note2: Mine is also bound to an enable or disable variable.


If you remove the references to ro_clientmodules_extend then you don’t need the complex additions to the binding although you will not then pass the variable back to the command procedure which could limit what you can do.. hence I left it in as an example.

WPF MessageBox

To create a WPF MessageBox use:

MessageBoxResult dialogResult = System.Windows.MessageBox.Show("Are you sure you wish to delete this?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
if (dialogResult == MessageBoxResult.Yes)
{
    System.Windows.MessageBox.Show("Delete operation Worked");
}
else
{
    System.Windows.MessageBox.Show("Delete operation Terminated");
}

Binding a TabItem visibility in XAML

This is a quick demo of how to bind your TabItem visibility so that you can quickly change what’s visible using variable in your viewmodel code.

Create a Converter in a new class file  Converters:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows;

namespace ConfigurationModule.Converters
{
    [ValueConversion(typeof(bool), typeof(Visibility))]
    public class BoolToVisibilityConverter : IValueConverter
    {

        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is bool && targetType == typeof(Visibility))
            {
                bool val = (bool)value;
                if (val)
                    return Visibility.Visible;
                else
                    if (parameter != null && parameter is Visibility)
                        return parameter;
                    else
                        return Visibility.Collapsed;
            }
            throw new ArgumentException("Invalid argument/return type. Expected argument: bool and return type: Visibility");
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Visibility && targetType == typeof(bool))
            {
                Visibility val = (Visibility)value;
                if (val == Visibility.Visible)
                    return true;
                else
                    return false;
            }
            throw new ArgumentException("Invalid argument/return type. Expected argument: Visibility and return type: bool");
        }
        #endregion
    }
}

 
In the XAML header page add:

xmlns:converters="clr-namespace:.Converters"

 
In the XAML Tabcontrol:


 


C# delegates to update the UI from a thread

The Following enables a thread to update the main UI using a delegate.  In this case MyTextBox.Text has an “x” added to its text property.

Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => this.MyTextBox.Text += "x"));

Apply Changes Made to a Detached Object

This allows changes to be stored based on the original object and changed object:

See:  https://msdn.microsoft.com/en-us/library/vstudio/bb896248%28v=vs.100%29.aspx

private static void ApplyItemUpdates(SalesOrderDetail originalItem,
SalesOrderDetail updatedItem)
{
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
context.SalesOrderDetails.Attach(updatedItem);
// Check if the ID is 0, if it is the item is new.
// In this case we need to chage the state to Added.
if (updatedItem.SalesOrderDetailID == 0)
{
// Because the ID is generated by the database we do not need to
// set updatedItem.SalesOrderDetailID.
context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added);
}
else
{
// If the SalesOrderDetailID is not 0, then the item is not new
// and needs to be updated. Because we already added the
// updated object to the context we need to apply the original values.
// If we attached originalItem to the context
// we would need to apply the current values:
// context.ApplyCurrentValues(“SalesOrderDetails”, updatedItem);
// Applying current or original values, changes the state
// of the attached object to Modified.
context.ApplyOriginalValues(“SalesOrderDetails”, originalItem);
}
context.SaveChanges();
}
}