This is a mirror of official site: http://jasper-net.blogspot.com/

Yes you can write Inline Code in XAML

| Tuesday, December 21, 2010
A couple of days ago I was spreading the WPF goodness and was talking about how MVVM (Model-View-ViewModel) helps promote separation of concerns by removing the need for the code-behind file from the associated XAML file.  After my statement someone replied with the following question, “So why even have it there, can you just delete it?”.  Obviously I replied yes, you absolutely can delete the code-behind file from a XAML file and the application will still work.  Then they replied, “That’s cool I guess, but what about the code that needs to execute, such as event handlers?”.  Naturally I brought up the fact that using MVVM you don’t use event handlers, but as most developers do, they said, “Well what if I really needed it?”.  My reply to that question was, “If you really had to, it is possible to write inline code inside the XAML file”.

They looked at me in amazement, “Really?”.  Apparently that is a little known fact about WPF.  Yes, it is absolutely possible to write inline code inside a XAML page without the need for a code-behind file, and everything will work as expected.  I quickly realized that his was going somewhere I didn’t want it to go.  I knew what was coming next; they asked me to show them how to do it. Uggg…

Okay here is the deal; what I am about to show you is not recommended.  It goes against everything I have been teaching in the community, but if you are curious how to actually do this, it is quit simple.

<Grid>
   <!–Define the button content –>
   <Button Width="133" Height="24" Name="btnExitApp" Click="btnExitApp_Clicked" Content="Exit Application"/>
   <!–The C# implementation of the button's Click event handler. –>

   <x:Code>
       <![CDATA[            
           private void btnExitApp_Clicked(object sender, RoutedEventArgs e)
           {
               // Get a handle to the current app and shut it down.
               Application.Current.Shutdown();
           }
       ]]>
   </x:Code>

</Grid>


Read more:  <elegantc*de>

Posted via email from .NET Info

0 comments: