Category Archives: C#

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();
}
}

Adding a PRISMPROP snippet to VS C#

This sets up visual studio to add a snippet that will put in a prism style property really quickly and easily and help set this up fast!

FOLDER:

Documents\Visual Studio xxxx\Code Snippets\Visual C#\My Code Snippets\

FILE: prismprop.snippet

XML:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<CodeSnippets  xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>
<CodeSnippet Format=”1.0.0″>
<Header>
<Title>prismprop</Title>
<Shortcut>prismprop</Shortcut>
<Description>Code snippet for property and backing field</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>Prop</Default>
</Literal>
<Literal>
<ID>field</ID>
<ToolTip>The variable backing this property</ToolTip>
<Default>_myVar</Default>
</Literal>
</Declarations>
<Code Language=”csharp”><![CDATA[private $type$ $field$;

public $type$ $property$
{
get { return $field$;}
set { SetProperty<$type$>(ref $field$, value);}
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

 

XAML relative size

How to size components to fit relative to parents in the tree:

Width=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}},Path=ActualWidth}”

Height=”{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid}},Path=ActualHeight}”