<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Richard Dutton &#187; C#</title>
	<atom:link href="http://www.dutton.me.uk/category/software-development/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dutton.me.uk</link>
	<description>Software Engineering, Photography, Travel, Stuff...</description>
	<lastBuildDate>Sat, 13 Feb 2010 08:45:56 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Handling events from within a ControlTemplate in WPF</title>
		<link>http://www.dutton.me.uk/2010/02/13/handling-events-from-within-a-controltemplate-in-wpf/</link>
		<comments>http://www.dutton.me.uk/2010/02/13/handling-events-from-within-a-controltemplate-in-wpf/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 07:00:42 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[button]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[event]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[events inside a ControlTemplate]]></category>
		<category><![CDATA[events within a ControlTemplate]]></category>
		<category><![CDATA[GetTemplateChild]]></category>
		<category><![CDATA[OnApplyTemplate]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[RoutedEvent]]></category>
		<category><![CDATA[RoutedEventhandler]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=323</guid>
		<description><![CDATA[Here&#8217;s an interesting one that had me stumped for a few hours.
Following on from my previous post, where I explained how to create a ControlTemplate to style a TextBox in WPF, I&#8217;ve got an object, TextEntryBox, which dervies from a TextBox (it provides some custom event handlers when text is entered, but to all intents [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s an interesting one that had me stumped for a few hours.</p>
<p>Following on from my <a href="http://www.dutton.me.uk/2010/02/13/how-to-create-a-controltemplate-for-a-wpf-textbox/" target="_blank">previous post</a>, where I explained how to create a ControlTemplate to style a TextBox in WPF, I&#8217;ve got an object, TextEntryBox, which dervies from a TextBox (it provides some custom event handlers when text is entered, but to all intents and purposes, it&#8217;s a regular TextBox).</p>
<p>I wanted to style my TextEntryBox, this time including a button within my ControlTemplate (this will eventually toggle an on-screen keyboard pop-up, but that&#8217;s another blog post!). I came up with this:<br />
<span id="more-323"></span></p>
<pre name="code" class="xml">
<Style TargetType="{x:Type my:EntryTextBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type my:EntryTextBox}">
                <DockPanel>
                    <Border BorderThickness="1"
                    	HorizontalAlignment="Stretch"
                    	BorderBrush="DarkGray"
                    	Background="White"
                    	Width="100">
                        <DockPanel>
                            <Button x:Name="PART_KeyboardPopupButton"
                            	DockPanel.Dock="Right"
                            	Width="15"
                            	Height="10"/>
                            <ScrollViewer Margin="0"
                            	Background="Transparent"
                            	HorizontalAlignment="Stretch"
                            	x:Name="PART_ContentHost"/>
                        </DockPanel>
                    </Border>
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</pre>
<p>All&#8217;s well and good, until I want to try and handle the Click event for that button within my TextEntryBox class. Even Matthew MacDonald&#8217;s &#8220;Pro WPF in C# 2008&#8243; which has proved a lifesaver for all things WPF since I&#8217;ve been working with this technology only had the following words of wisdom;</p>
<blockquote><p>&#8220;You can&#8217;t attach event handlers in the control template. Instead, you&#8217;ll need to give your elements recognizable names and attach event handlers to them programmatically in the control constructor&#8221;</p></blockquote>
<p>But whatever I tried I couldn&#8217;t access the event in my constructor, until I remembered the seperation between the visual and logical trees in WPF.</p>
<p>The template is applied at runtime, and so elements contained within it it are part of the visual tree. My class, and therefore my class&#8217; constructor is executed within the logical tree, so I needed to attach my event handler after the template had been applied. You can do this by overriding OnApplyTemplate in your class, obtain the template that&#8217;s being applied, and then you have access to the named button&#8217;s events, like this:</p>
<pre name="code" class="c-sharp">
public override void OnApplyTemplate()
{
    DependencyObject d = GetTemplateChild("PART_KeyboardPopupButton");
    if (d != null)
    {
        (d as Button).Click += new RoutedEventHandler(KeyboardPopupButton_Click);
    }

    base.OnApplyTemplate();
}
</pre>
<p>Note the null check, as someone could have applied a completely different template to the object.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2010/02/13/handling-events-from-within-a-controltemplate-in-wpf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to create a ControlTemplate for a WPF TextBox</title>
		<link>http://www.dutton.me.uk/2010/02/13/how-to-create-a-controltemplate-for-a-wpf-textbox/</link>
		<comments>http://www.dutton.me.uk/2010/02/13/how-to-create-a-controltemplate-for-a-wpf-textbox/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 06:00:10 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[ContentHost]]></category>
		<category><![CDATA[ControlTemplate]]></category>
		<category><![CDATA[PART_ContentHost]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ScrollViewer]]></category>
		<category><![CDATA[style]]></category>
		<category><![CDATA[TextBox]]></category>
		<category><![CDATA[x:Name]]></category>
		<category><![CDATA[x:Name="Part_ContentHost"]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=325</guid>
		<description><![CDATA[This is a short post, but has one specific piece of information I want to keep.
Q: If you want to create a ControlTemplate to provide a custom style for a TextBox, how do you specify where the text goes when it&#8217;s used in WPF?
A: The answer was hidden in the depths of the MSDN Documentation. [...]]]></description>
			<content:encoded><![CDATA[<p>This is a short post, but has one specific piece of information I want to keep.</p>
<p>Q: If you want to create a ControlTemplate to provide a custom style for a TextBox, how do you specify where the text goes when it&#8217;s used in WPF?</p>
<p>A: The answer was hidden in the depths of the MSDN Documentation. You have to include a &lt;ScrollViewer&gt; within your ControlTemplate with an x:Name value of &#8220;PART_ContentHost&#8221;.</p>
<p>Here&#8217;s a noddy example:</p>
<pre name="code" class="xml">
<Style TargetType="{x:Type TextBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <DockPanel>
                    <Border BorderThickness="1"
                               BorderBrush="DarkGray"
                               Background="White"
                               Width="100">
                        <DockPanel>
                            <ScrollViewer Background="Transparent"
                                               HorizontalAlignment="Stretch"
                                               x:Name="PART_ContentHost"/>
                        </DockPanel>
                    </Border>
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2010/02/13/how-to-create-a-controltemplate-for-a-wpf-textbox/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C#&#8217;s Null-Coalescing (??) Operator</title>
		<link>http://www.dutton.me.uk/2009/04/22/cs-null-coalescing-operator/</link>
		<comments>http://www.dutton.me.uk/2009/04/22/cs-null-coalescing-operator/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 07:31:10 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[c# operator]]></category>
		<category><![CDATA[null]]></category>
		<category><![CDATA[null coalescing]]></category>
		<category><![CDATA[null coalescing operator]]></category>
		<category><![CDATA[nullable]]></category>
		<category><![CDATA[nullable type]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=212</guid>
		<description><![CDATA[Although I&#8217;ve always been a big fan of the ternary operator, kudos goes to the Refactoriser (you know who you are!) for pointing me in the direction of an even more effective way of obfsuca^H^H^H tidying up my code; the ?? operator.
The null-coalescing operator (to call it by its more catchy name) allows you to [...]]]></description>
			<content:encoded><![CDATA[<p>Although I&#8217;ve always been a big fan of the <a href="http://msdn.microsoft.com/en-us/library/ty67wk28(VS.80).aspx" target="_blank">ternary operator</a>, kudos goes to the Refactoriser (you know who you are!) for pointing me in the direction of an even more effective way of obfsuca^H^H^H tidying up my code; the <a href="http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx" target="_blank">?? operator</a>.</p>
<p>The null-coalescing operator (to call it by its more catchy name) allows you to provide an alternative value in the event that the reference type object (or nullable value type) you are trying to access evaluates to null. So instead of having to do something like this:</p>
<pre name="code" class="csharp">
            int? myNullableInt = null;
            int myInt;

            if (myNullableInt == null)
            {
                myInt = -1;
            }
            else
            {
                myInt = (int)myNullableInt;
            }
</pre>
<p>You can do this in-line:</p>
<pre name="code" class="csharp">
myInt = myNullableInt ?? -1;
</pre>
<p>Apologies for the heavily contrived and quite pointless example, but at least it gets the syntax down and should make it apparent how useful this operator can be when dealing with a mixture of nullable and non-nullable types.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2009/04/22/cs-null-coalescing-operator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making a function call on another thread using the C# Dispatcher class</title>
		<link>http://www.dutton.me.uk/2009/03/30/making-a-function-call-on-another-thread-with-the-c-dispatcher-class/</link>
		<comments>http://www.dutton.me.uk/2009/03/30/making-a-function-call-on-another-thread-with-the-c-dispatcher-class/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 18:00:09 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Dispatcher]]></category>
		<category><![CDATA[multi-threaded]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=181</guid>
		<description><![CDATA[There may be a situation when you need to execute a function on a different thread, such as ensuring that calls across the interface between a multi-threaded dll and its single-threaded user are made on the same, single thread.  To achive this, you can use the target thread&#8217;s Dispatcher object as follows:

Create a delegate [...]]]></description>
			<content:encoded><![CDATA[<p>There may be a situation when you need to execute a function on a different thread, such as ensuring that calls across the interface between a multi-threaded dll and its single-threaded user are made on the same, single thread.  To achive this, you can use the target thread&#8217;s Dispatcher object as follows:</p>
<ol>
<li>Create a delegate of the function you wish to be able to call:
<pre name="code" class="c-sharp">
public delegate void MyDelegate(int i, string str);
public class TargetThreadClass
{
    public TargetThreadClass()
    {
        MyDelegate del = new MyDelegate(this.FuncToExec);
    }
    public void FuncToExec(int i, string str)
    {
       // Do something
   }
}</pre>
</li>
<li>Within the target thread, create an instance of a Dispatcher object and set it to the thread&#8217;s current dispatcher:
<pre name="code" class="c-sharp">
Dispatcher UserDispatcher = Dispatcher.CurrentDispatcher;</pre>
<p>Then pass this dispatcher, along with the delegate into the source thread.</li>
<li>Then to call FuncToExec on the target thread, use:
<pre name="code" class="c-sharp">
UserDispatcher.Invoke(del, new object[] { 123, "arg string"});</pre>
<p>Where the first parameter of Invoke is the delegate itself and the second an array of the delegate&#8217;s parameters (if any), in this example the delegate takes an int and a string.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2009/03/30/making-a-function-call-on-another-thread-with-the-c-dispatcher-class/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Non-blocking keyboard input in C#</title>
		<link>http://www.dutton.me.uk/2009/02/24/non-blocking-keyboard-input-in-c/</link>
		<comments>http://www.dutton.me.uk/2009/02/24/non-blocking-keyboard-input-in-c/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 17:30:39 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[console keyboard input]]></category>
		<category><![CDATA[Console.KeyAvailable]]></category>
		<category><![CDATA[Console.ReadKey]]></category>
		<category><![CDATA[non-blocking]]></category>
		<category><![CDATA[non-blocking keyboard input]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=109</guid>
		<description><![CDATA[I know this one is pretty noddy, but these posts are as much a way of me storing code snippets I might need quickly in the future as any form of &#8216;public service&#8217; so I&#8217;ll post it anyway.
I quite frequently want to capture key presses in my apps, and to do this I use Console.ReadKey [...]]]></description>
			<content:encoded><![CDATA[<p>I know this one is pretty noddy, but these posts are as much a way of me storing code snippets I might need quickly in the future as any form of &#8216;public service&#8217; so I&#8217;ll post it anyway.</p>
<p>I quite frequently want to capture key presses in my apps, and to do this I use Console.ReadKey which returns a nice ConsoleKeyInfo object to tell me what&#8217;s just been pressed. The problem is this call blocks until a key has been pressed and sometimes I don&#8217;t want to block out the main execution thread or have to create a separate thread *just* to handle the keyboard input.</p>
<p>This is where Console&#8217;s KeyAvailable property comes in.  It returns true if there is a key press available in the input stream without blocking allowing you to do something like:</p>
<pre name="code" class="c-sharp">
while (true)
{
    if (Console.KeyAvailable)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        switch (key.Key)
        {
            case ConsoleKey.F1:
                Console.WriteLine("You pressed F1!");
                break;
            default:
                break;
        }
    }
    // Do something more useful
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2009/02/24/non-blocking-keyboard-input-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Returning errorlevels from C# applications</title>
		<link>http://www.dutton.me.uk/2009/01/22/returning-errorlevels-from-c-applications/</link>
		<comments>http://www.dutton.me.uk/2009/01/22/returning-errorlevels-from-c-applications/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 16:19:58 +0000</pubDate>
		<dc:creator>richard</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[batch file]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[errorlevel]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.dutton.me.uk/?p=20</guid>
		<description><![CDATA[Something came up today which turned out to be a bit of a blast from the past. If you want to check the return value of a C# console application (for use in an old school batch file for example) you can&#8217;t rely on the return value of main (as you would in C for [...]]]></description>
			<content:encoded><![CDATA[<p>Something came up today which turned out to be a bit of a blast from the past. If you want to check the return value of a C# console application (for use in an old school batch file for example) you can&#8217;t rely on the return value of main (as you would in C for example), but have to set the value of System.Environment.ExitCode instead. The advantage to this over a single return statement is this call sets the exit code and won&#8217;t actually exit your program at that point, see below.</p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
	// program code...
	// now set the return value to 1
	System.Environment.ExitCode = 1
}
</pre>
<p>This example returns 1, which can then be picked up by some good ol&#8217; fashioned batch command-goodness. I&#8217;m already reminiscing back to my 1000+ line BBS mailer batch file back in 1995!</p>
<p>Also came across <a href="http://tldp.org/LDP/abs/html/exitcodes.html" target="_blank">this</a> which provides guidance on the special meanings of some exit codes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dutton.me.uk/2009/01/22/returning-errorlevels-from-c-applications/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
