The ViewController and XAML

About two nights ago, I learned how to use an external XAML in  a WPF application. It was so simple. Just read the XAML, parse it, and then wire the elements to your code.  Now if this is how we are supposed to code in WPF, then I might just as well stick to WinForms.

Fortunately XAML was not designed like Winforms or even Webforms.  The FrameworkElement in WPF has a DataContext property which is an object type. This means we can feed it any kind of object that fits our purpose.  The great thing about this is, XAML has the capability to bind all the elements in the object tree to the root element's DataContext property.  All we have to do is bind an element's property or properties to the corresponding property or properties of the object concerned like so:

<StackPanel
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ListBox
        Name="listBox1"
        IsSynchronizedWithCurrentItem="true"
        ItemsSource="{Binding Path=Employees}"/>
    <Button
        CommandParameter="{Binding ElementName=listBox1}"
        Command="{Binding Path=DeleteEmployee}"
        Content="Delete"/>
</StackPanel>

Assuming we have a class called CompanyViewController that exposes the properties Employees (ListCollectionView) and DeleteEmployee (ICommand), and the XAML is stored in EmployeeListView.xaml, the code to drive this XAML could simply look like this:

class EmployeeListView(Window):
	def constructor(company as Company):
		# parse the element tree via the XamlReader
		streamReader = StreamReader("EmployeeListView.xaml")
		xmlreader = XmlReader.Create(streamReader)		
		view as Panel= XamlReader.Load(xmlreader)
                
                # give the view something to chew on
		view.DataContext = CompanyViewController(company)
		
		# display the view in the window
		self.Content = view

If you are a TDD kind of guy, you have to feel that tingling sensation! 


        

        
Published 10-05-2006 10:58 PM by smash
Filed under: , , , ,