Posts tagged ‘C#’

Composite WPF Presentation Model item template

Neat little template I designed for use at work which is an improvement over the ViewModel code snippet.

Download PresentationModel item template

How to use

It is a bit unusual the way I have written this. Instead of specifying the file name for the item, it is the view name that is to be used.

When prompted for the ViewName, specifying “MainWindow” will create:

A xaml user control called MainWindowView.xaml.

An interface called IMainWindowView.

An interface called IMainWindowViewModel.

A class called MainWindowViewModel.

(Some of this is very similar to the ViewModel code snippet)

Interface Properties

Basically rip-offs of the prop and propg code snippets you get with Visual Studio but without the scope or accessor keywords.

iprop

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>iprop</Title>
			<Shortcut>iprop</Shortcut>
			<Description>Code snippet for an automatically implemented property on an interface</Description>
			<Author>Alex Boyne-Aitken</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>MyProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[$type$ $property$ { get; set; }$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

ipropg

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>ipropg</Title>
			<Shortcut>ipropg</Shortcut>
			<Description>Code snippet for an automatically implemented property with a 'get' accessor for interfaces</Description>
			<Author>Alex Boyne-Aitken</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>MyProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[$type$ $property$ { get; }$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

View model property

Because I am so lazy :P

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>View model property snippet</Title>
			<Shortcut>vmprop</Shortcut>
			<Description></Description>
			<Author>Alex Boyne-Aitken</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
        <Literal>
          <ID>name</ID>
          <ToolTip>Property name</ToolTip>
          <Default>Field</Default>
        </Literal>
        <Literal>
          <ID>field</ID>
          <ToolTip>Field name</ToolTip>
          <Default>field</Default>
        </Literal>
        <Literal>
          <ID>type</ID>
          <ToolTip>Type</ToolTip>
          <Default>object</Default>
        </Literal>
			</Declarations>
			<Code Language="csharp">
        <![CDATA[
    $type$ $field$;
    public $type$ $name$
    {
        get { return $field$; }
        set
        {
            if ($field$ == value)
                return;

            $field$ = value;
            SendPropertyChanged("$name$");
        }
    }
			$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

Closeable TabItems using CompositeWPF

On a project I am working on at the moment, I needed to allow the user to open and close views. As I was using the Composite Application Block injecting views into a tab control was really easy. Closing them was not.

To remove a view from a region you need two things, the RegionName and the View.

This article helped me a lot when engineering this approach:

http://blogs.infosupport.com/blogs/willemm/archive/2008/07/31/Creating-closeable-tabitems-for-use-in-CompositeWPF.aspx

However the RegionManager.GetRegionName did not work against the TabItem. I always got null, I am assuming this is a change that was made during the time the article was posted. Using the TabControl however worked.

But you cannot easily bind to two things (the TabControl and the TabItem).

To achieve my goal I used the XAML from the article and changed it little

<DataTemplate x:Key="CustomTabHeader">
<StackPanel Orientation="Horizontal">
<ContentPresenter>
<ContentPresenter.Content>
<Binding Path="Content.Model.HeaderText">
<Binding.RelativeSource>
<RelativeSource Mode="FindAncestor"
AncestorType="{x:Type TabItem}"/>
</Binding.RelativeSource>
</Binding>
</ContentPresenter.Content>
</ContentPresenter>
<Button Margin="8,0,0,0"
Command="{Binding Path=Model.CloseTabCommand.Command, ElementName=ThisControl}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type TabItem}}}"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center">
<Grid>
<Canvas Width="8" Height="8">
<Line X1="2" X2="6" Y1="2" Y2="6" Stroke="Black" StrokeThickness="1"/>
<Line X1="6" X2="2" Y1="2" Y2="6" Stroke="Black" StrokeThickness="1"/>
</Canvas>
</Grid>
</Button>
</StackPanel>
</DataTemplate>

<Style TargetType="TabItem">
<Style.Setters>
<Setter Property="HeaderTemplate"
Value="{StaticResource CustomTabHeader}"/>
</Style.Setters>
</Style>

The only difference is where I go for my commands and header text. In my project I have an interface that describes a headed content item.

The change really is in the code for closing the view:

class CloseTabCommand : CommandModelBase
{
private readonly IRegionManager regionManager;

public CloseTabCommand(IRegionManager regionManager)
{
this.regionManager = regionManager;
}

public override void OnExecute(object sender, ExecutedRoutedEventArgs e)
{
var tabItem = (TabItem)e.Parameter;
var tabControl = (TabControl) e.Source;

var regionName = RegionManager.GetRegionName(tabControl);

regionManager.Regions[regionName].Remove(tabItem.Content);
}
}

In the end the solution boiled down to being really simple. You still bind to the tab item but the source is the tab control.

There will be some drawbacks to this approach. If a key binding is setup for this command then the source could change, so care should be taken.

But this works and it will do for the time being until I think of a better solution.

Generic WeakReference

I always felt that I wanted to use the WeakReference class a lot like the Nullable<T> class.


internal class WrappedWeakReference<T> : WeakReference
 {
 public WrappedWeakReference(T target)
 : base(target)
 {
 }

 public new T Target
 {
 get { return (T) base.Target; }
 set { base.Target = value; }
 }

 public static implicit operator WrappedWeakReference<T>(T item)
 {
 return new WrappedWeakReference<T>(item);
 }
 }

This allows you to write things like:

 private WrappedWeakReference<MyObject> weakMyObject;

 public void Foo()
 {
 weakMyObject = new MyObject();
 }

 public void Bar()
 {
 weakMyObject.Target.SomeProperty....etc
 }
}

I think its nice idea.

However never did actually use this, I implemented the solution in a different manner where I did not need a weakreference, so this never got tested. I am not sure if it would work.

Empty object code snippet pattern

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>Empty pattern snippet</Title>
			<Shortcut>empty</Shortcut>
			<Description>Creates an empty static property and nested null object </Description>
			<Author>Alex Boyne-Aitken</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Class type</ToolTip>
					<Default>Class</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[
			private static readonly $type$ empty = new NullObject();
public static $type$ Empty { get { return empty; } }

private class NullObject : $type$
{
}
			$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

Download

View and ViewModel pattern code snippet

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>ViewModel pattern snippet</Title>
			<Shortcut>viewmodel</Shortcut>
			<Description>Creates a view and viewmodel interface and a concreate view model </Description>
			<Author>Alex Boyne-Aitken</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>name</ID>
					<ToolTip>Base name</ToolTip>
					<Default>Class</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[
    public interface I$name$View
    {
        I$name$ViewModel Model { get; set; }
    }

    public interface I$name$ViewModel
    {
        I$name$View View { get; }
    }

    class $name$ViewModel : I$name$ViewModel
    {
        private readonly I$name$View view;

        public $name$ViewModel(I$name$View view)
        {
            this.view = view;
            view.Model = this;
        }

        public I$name$View View
        {
            get { return view; }
        }
    }
			$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

Download