Today I Learned: WPF Templates

Ugh XAML. Functional its really nice, and with Windows Presentation Foundation, it makes for some really awesome GUIs. You can do all kinds of cool data binding and automatically display information. A few projects about a year or so back using WPF XAML and C# is what reinvigorated my love for programming, which admittedly was looking down for awhile. But damn is it messy. Quick example: You can make an excel grid automatically display the data members in your class. If you had a class of Customers, with all kinds of Customer info, you can bind the grid to a list/array or collection of Customer and have it automatically display this info. So awesome! But, what if you wanted a specific kind of grid with specific properties? It’s also easy to do, its called Styling. And I knew about it for awhile, but this was driving me up a wall to find – I wanted specific column headers which you cant style for some reason when you bind them. So I made a workaround.

<Window.Resources>

<DataGrid x:Key=”MyCustomGrid” ItemsSource=”{Binding}”>

<DataGrid.Columns>

<DataGridTemplateColumn Header=”Name”>

<Label Content =”{Binding Path=fullName}”/>

</DataGridTemplateColumn>

</DataGrid.Columns>

</DataGrid>

</Windows.Resources>

 

Now in the “code-behind”, I can just call something like new ControlItem(), set the content to “MyCustomGrid”, and I have my cool DataGrid. From there I can set the data context to Customers and only the Customer’s name will show up. I can do all kinds of other stuff like make the column colored red or have specific sorting, ect. Its all good stuff but sometimes XAML is super messy and documentation is like all over the place with this stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *