π Lecture 28 β Localizing Binary Resources and Logical Resources
π Overview: This lecture covers two major WPF topics: how to localize binary resources using satellite assemblies and the LocBaml tool, and how to use logical resources (including static vs dynamic resources) to share objects like brushes across elements. Understanding these concepts is essential for building professional, multi-language WPF applications and for efficient UI styling.
ποΈ Topics Covered
Localizing binary resources using satellite assemblies, setting UICulture in project files, using LocBaml to parse and generate localized resource assemblies, and testing localization by changing thread culture. Then, the lecture introduces WPF logical resources: defining and using resources like SolidColorBrush and LinearGradientBrush in XAML, using StaticResource and DynamicResource markup extensions, resource lookup behavior, sharing vs non-sharing with x:Shared, and procedural code equivalents for resource access. Finally, it contrasts static and dynamic resources with examples of system colors and equivalent C# code.
π Lecture Summary
Localizing Binary Resources
Localizing binary resources means separating them into satellite assemblies and using LocBaml to manage string localization. To build a satellite assembly automatically, set the UICulture in the project file. Open the project file in a text editor and add <UICulture>en-US</UICulture> under the property group (affects Debug, Release, etc.). After rebuilding, youβll find an en-US folder containing the satellite assembly named assemblyname.resources.dll. Also mark the assembly with the NeutralResourcesLanguage attribute matching the default culture.
Next, apply a Uid directive to any element needing localization. Run msbuild /t:updateuid projectname.csproj to generate unique IDs. Then run Locbaml /parse projectname.g.en-US.resources /out:en-US.csv to extract strings to a CSV file. After editing/translating the CSV, run Locbaml /generate Project-Name.resources.dll /trans:fr-CA.csv /cul:fr-CA to create the localized satellite assembly. Copy the assembly with a name matching the locale (e.g., fr-CA). To test, set System.Threading.Thread.CurrentThread.CurrentUICulture and CurrentCulture to an instance of the desired CultureInfo.
π‘ Why this matters: Without this technique, every language version would require a separate codebase; satellite assemblies allow single-codebase multi-language deployment.
π Definition β Satellite assembly: A DLL containing localized resources (like strings and images) for a specific culture, deployed alongside the main application assembly.
π Example: For a project named MyApp with default culture en-US, setting <UICulture>en-US</UICulture> creates en-US\MyApp.resources.dll. To localize to French-Canadian, edit the CSV then generate fr-CA\MyApp.resources.dll.
Logical Resources Introduction
Logical resources are introduced by WPF. They are arbitrary .NET objects stored and named in an elementβs Resources property. They are meant to be shared by multiple child objects. Both FrameworkElement and FrameworkContentElement have a Resources property. Resources are often Style or data providers. First examples use simple brushes. Much like CSS, they allow sharing objects across many elements.
For example, without resources, every button must repeat Background="Yellow" and BorderBrush="Red". With a Window.Resources dictionary, you define:
<Window.Resources>
<SolidColorBrush x:Key="backgroundbrush">Yellow</SolidColorBrush>
<SolidColorBrush x:Key="borderbrush">Red</SolidColorBrush>
</Window.Resources>
Then apply via Background="{StaticResource backgroundbrush}" on each button.
You can also use a LinearGradientBrush as a resource:
<LinearGradientBrush x:Key="backgroundbrush" StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="Blue" Offset="0"/>
<GradientStop Color="White" Offset="0.5"/>
<GradientStop Color="Red" Offset="1"/>
</LinearGradientBrush>
Now changing the brush in one place affects all elements using that resource.
π Definition β StaticResource markup extension: Looks up a resource by key at load time by walking the logical tree (element β parent β application level β system resources). The closest resource to the element is chosen. For maximum sharing, define resources at root level or in Application.Resources.
β οΈ Important: For multi-threaded scenarios, use either Frozen objects or set x:Shared="False" to avoid thread-safety issues.
Static vs Dynamic Resources
StaticResource is resolved once at load time; DynamicResource is reapplied every time the resource changes. There is nothing special about the resources themselves β only whether you want to see updates. DynamicResource has more overhead but supports demand loading (resources loaded only when needed). Dynamic resources can only be used to set dependency property values. Static resources can even abstract whole controls.
π‘ Why this matters: Choose StaticResource for performance when the resource never changes; choose DynamicResource for themes, system colors, or resources that change at runtime.
π Definition β Dependency property: A property that is registered with the WPF property system and supports features like data binding, styling, and animation.
Resource Sharing and Forward References
With StaticResource, forward references are not supported β the resource must be defined before it is used. Also, an Image control can only have one parent, so you cannot share the same instance across multiple elements unless you use x:Shared="False".
For example, with x:Shared="False", a new instance of the Image is created each time:
<Window.Resources>
<Image x:Shared="False" x:Key="zoom" Height="21" Source="zoom.gif"/>
</Window.Resources>
<StackPanel>
<StaticResource ResourceKey="zoom"/>
<StaticResource ResourceKey="zoom"/>
<StaticResource ResourceKey="zoom"/>
</StackPanel>
With DynamicResource, forward references are possible because the lookup happens at runtime:
<Window Background="{DynamicResource backgroundbrush}">
<Window.Resources>
<SolidColorBrush x:Key="backgroundbrush">Yellow</SolidColorBrush>
</Window.Resources>
</Window>
Procedural Code Resource Access
In C#, you can add resources and access them in several ways:
-
Add resources directly to Window.Resources:
Window.Resources.Add("backgroundbrush", new SolidColorBrush(Colors.Yellow)); -
FindResource method (walks the logical tree):
button.Background = (Brush)button.FindResource("backgroundbrush");β οΈ The button must be added to the visual tree before calling FindResource.
-
SetResourceReference method (dynamic behavior):
button.SetResourceReference(Button.BackgroundProperty, "backgroundbrush"); -
Direct dictionary access (no tree walk):
button.Background = (Brush)window.Resources["backgroundbrush"];
System Colors and Equivalent Patterns
Several XAML patterns exist for accessing system colors, each with C# equivalents:
| XAML | C# Equivalent |
|---|---|
Background="SystemColors.WindowBrush" | button.Background = (Brush)new BrushConverter().ConvertFrom("SystemColors.WindowBrush"); |
Background="{x:Static SystemColors.WindowBrush}" | button.Background = SystemColors.WindowBrush; |
Background="{StaticResource SystemColors.WindowBrushKey}" | button.Background = (Brush)FindResource("SystemColors.WindowBrushKey"); |
Background="{StaticResource {x:Static SystemColors.WindowBrush}}"} | button.Background = (Brush)FindResource(SystemColors.WindowBrush); |
Background="{StaticResource {x:Static SystemColors.WindowBrushKey}}" | button.Background = (Brush)FindResource(SystemColors.WindowBrushKey); |
Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" | button.SetResourceReference(Button.BackgroundProperty, SystemColors.WindowBrushKey); |
β Key Takeaways
Resources are extremely important in professional WPF applications. They enable localization, increase productivity by consolidating and sharing objects across multiple elements, and are the foundation for styles and data binding. For localization, use UICulture, LocBaml, and satellite assemblies. For logical resources, remember that StaticResource resolves at load time and is faster, while DynamicResource resolves at runtime and supports updates. Use x:Shared="False" to create multiple instances of a resource that cannot be shared (e.g., UI elements with single-parent constraints). System colors can be accessed via multiple XAML markup patterns, with StaticResource being the most common for theming.
π§ Quick Revision Questions
- What is the purpose of setting
<UICulture>in a WPF project file, and what does it generate during build? - What command extracts resource strings to a CSV file for localization editing?
- What is the difference between StaticResource and DynamicResource in terms when the resource is resolved?
- Why must you use
x:Shared="False"when defining an Image as a resource if you want to use it multiple times in the same parent? - In C#, what method should you call on a Button to get a resource that walks the logical tree, and why must the button be in the visual tree first?
π Lecture 29 β Data Binding
π Overview: This lecture explores data binding in WPF, a mechanism that connects arbitrary .NET objects (like collections, XML files, or database tables) to visual elements. It explains how binding simplifies UI development by automating synchronization between data sources and target properties, eliminating manual iteration and refresh logic.
ποΈ Topics Covered
The lecture covers the fundamentals of data binding, including setting up bindings in procedural and XAML code, binding to collections and .NET properties, using DataContext for implicit sources, and applying String Formatting, Data Templates, and Value Converters to customize how data is displayed in UI elements like ListBox and Label.
π Lecture Summary
Chapter 29: Lecture 29 β Data Binding
Data binding connects arbitrary objects together, where "data" can be any .NET object: a collection object, XML file, web service, database table, custom object, or even a WPF element like a Button. The classic scenario is visually representing items (e.g. from a ListBox or DataGrid) from an XML file, database, or in-memory collection. Instead of iterating and adding items manually, you tell the ListBox to get its data from another source, keep them up to date, and format them.
Binding binds two properties together and keeps a communication channel open. You set up a Binding once and let it handle all the synchronization.
π Definition β Binding: A connection between two properties (source and target) that automatically synchronizes values, with source being the object/property providing data and target being the dependency property consuming it.
π Example β Procedural Code Binding:
// In MainWindow constructor
Binding binding = new Binding();
binding.Source = treeview;
binding.Path = new PropertyPath("selectedItem.Header");
// Attach to target property
Currentfolder.SetBinding(TextBlock.TextProperty, binding);
When an item with no header is selected, a default value is returned (no exception raised).
π Example β XAML Markup Extension:
<TextBlock x:Name="currentfolder"
Text="{Binding ElementName=treeview, Path=selectedItem.Header}" />
Alternative with Source:
<TextBlock Text="{Binding Source={x:Reference treeview}, Path=selectedItem.Header}" />
π Example β Binding for "Nothing selected":
<TextBlock Text="{Binding TargetNullValue=Nothing is selected.}" />
Key interfaces: System.ComponentModel.INotifyPropertyChanged β the source object should implement this interface (which has a single PropertyChanged event) for proper notification. The target must be a dependency property.
Binding to Collections
When binding a ListBox to a collection, ItemsSource (a dependency property) is used instead of Items (which is not a dependency property). The source property must implement INotifyCollectionChanged (also known as ObservableCollection).
π Example β Binding ListBox to Collection:
<ListBox x:Name="picturebox"
ItemsSource="{Binding Source={StaticResource photos}}" />
The DisplayMemberPath property can be used to improve display:
<ListBox x:Name="picturebox" DisplayMemberPath="Name"
ItemsSource="{Binding Source={StaticResource photos}}" />
π‘ Why this matters: You cannot mix Items and ItemsSource, but you always retrieve from Items. For richer display, use Data Templates or Value Converters.
Synchronization with Current Item
The IsSynchronizedWithCurrentItem property synchronizes selection across multiple ListBox controls:
<ListBox IsSynchronizedWithCurrentItem="True" DisplayMemberPath="Name" ... />
<ListBox IsSynchronizedWithCurrentItem="True" DisplayMemberPath="DateTime" ... />
<ListBox IsSynchronizedWithCurrentItem="True" DisplayMemberPath="Size" ... />
Note: scrolling is not synchronized, only the first selection.
Implicit Data Source: DataContext
The implicit data source is provided by DataContext. You set DataContext on a parent element and then don't specify Source or ElementName.
π Example β Using DataContext:
<StackPanel DataContext="{StaticResource photos}">
<Label x:Name="numitemslabel" Content="{Binding Path=Count}" />
<ListBox x:Name="picturebox" DisplayMemberPath="Name" ItemsSource="{Binding}" />
</StackPanel>
String Formatting
String Formatting works only if the target property is a string. Use {} to escape the initial brace.
π Example β String Formatting:
<TextBlock Text="{Binding StringFormat={}{0} item(s), Source={StaticResource photos}, Path=Count}" />
Or using element syntax:
<TextBlock.Text>
<Binding Source="{StaticResource photos}" Path="Count">
<Binding.StringFormat>{0} item(s)</Binding.StringFormat>
</Binding>
</TextBlock.Text>
String formatting can be used even without data binding:
<ListBox ItemStringFormat="{}{0:C}"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:Int32>-9</sys:Int32>
<sys:Int32>9</sys:Int32>
<sys:Int32>1234</sys:Int32>
<sys:Int32>1234567</sys:Int32>
</ListBox>
Data Templates
With Data Template, UI is auto-applied to arbitrary .NET objects when rendered. By setting these properties, you can swap in a complete new visual tree easily in XAML.
π Example β Basic Data Template:
<ListBox x:Name="picturebox" ItemsSource="{Binding Source={StaticResource photos}}">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="placeholder.jpg" Height="35" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
With a template, there is an implicit DataContext. Templates can be shared as resources and can even be auto-applied to some type by setting its DataType property. There is also HierarchicalDataTemplate that understands hierarchies (used with TreeView or Menu).
π Example β Template with Binding:
<ListBox x:Name="picturebox" ItemsSource="{Binding Source={StaticResource photos}}">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Path=fullpath}" Height="35" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Value Converters
Value Converters morph the source value into something else, introducing custom logic that can change type (e.g., a brush based on some enumeration).
π Definition β IValueConverter: An interface with two methods β Convert (source β target) and ConvertBack (target β source) β that transform values during binding.
π Example β CountToBackgroundConverter:
<Window.Resources>
<local:CountToBackgroundConverter x:Key="myconverter" />
</Window.Resources>
<Label Background="{Binding Path=Count, Converter={StaticResource myconverter},
Source={StaticResource photos}}" />
public class CountToBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (targetType != typeof(Brush))
throw new InvalidOperationException("The target must be a Brush!");
int num = int.Parse(value.ToString());
return (num == 0 ? Brushes.Yellow : Brushes.Transparent);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
β Key Takeaways
The most critical concept from this lecture is that data binding eliminates manual synchronization by establishing an automatic communication channel between source and target properties. You must understand that the target property must be a dependency property, and source objects should implement INotifyPropertyChanged for proper updates. For collections, use ItemsSource with ObservableCollection (which implements INotifyCollectionChanged). The DataContext provides an implicit data source that propagates through the element tree, while DisplayMemberPath offers simple display control. For richer customization, use Data Templates to define visual trees for data items, String Formatting for text output, and Value Converters (implementing IValueConverter) for transforming values.
π§ Quick Revision Questions
- What interface must a source object implement to properly notify property changes in WPF data binding, and what event does it provide?
- When binding a ListBox to a collection, why must you use
ItemsSourceinstead ofItems? - How does
DataContextsimplify XAML binding when you have multiple controls bound to the same data source? - What is the purpose of a
ValueConverterin WPF binding, and what two methods must it implement? - With a DataTemplate, what becomes the implicit DataContext inside the template, and why can't you mix
ItemsandItemsSource?
π Lecture 30 β Customizing Collection View and Data Providers
π Overview: This lecture explores advanced techniques for customizing collection views in WPF, including sorting, grouping, filtering, and navigation capabilities. It also introduces data providers (XmlDataProvider and ObjectDataProvider) for binding to various data sources, along with LINQ integration for modern data binding approaches.
ποΈ Topics Covered
The lecture covers customizing collection views with ICollectionView interface, SortDescriptions for sorting data, PropertyGroupDescription for grouping, Filter predicates for filtering, and navigation methods for managing current items. It also discusses CollectionViewSource for creating custom views, data providers including XmlDataProvider and ObjectDataProvider, and data binding with LINQ queries.
π Lecture Summary
Customizing Collection View
When IsSynchronizedWithCurrentItem is set to true, WPF inserts a default "view" that implements the ICollectionView interface. This view provides built-in support for sorting, grouping, filtering, and navigation operations on collections. Multiple views can exist for the same source object, allowing different presentations of the same data.
π‘ Why this matters: Collection views separate data presentation from data storage, enabling flexible UI patterns without modifying the underlying collection.
Sorting with SortDescriptions
The SortDescriptions property is a collection of SortDescription objects that specify fields and sort order. Multiple sort criteria can be combined, such as sorting by DateTime first, then by Name. A Clear() method returns the view to unsorted state. The example shows three buttons to sort by Name, DateTime, and Size with toggle functionality:
SortDescription sort = new SortDescription("Name", ListSortDirection.Ascending);
view.SortDescriptions.Add(new SortDescription("datetime", ListSortDirection.Descending));
view.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
π Definition β ICollectionView: An interface providing support for sorting, grouping, filtering, and navigation over a collection without modifying the source collection itself.
π Formula: View.SortDescriptions.Add(new SortDescription(propertyName, ListSortDirection)) β Adds a sorting rule that can combine multiple properties with ascending/descending order.
π Example: The sorthelper method gets the default view using CollectionViewSource.GetDefaultView(this.FindResource("photos")), checks if already sorted ascending by the current property, and toggles by clearing and adding descending order, otherwise clears and adds ascending order.
Grouping with PropertyGroupDescription
The GroupDescriptions property contains PropertyGroupDescription objects, but grouping has no visual effect without setting the GroupStyle property on the ListBox. The example shows grouping photos by DateTime:
view.GroupDescriptions.Clear();
view.GroupDescriptions.Add(new PropertyGroupDescription("datetime"));
XAML requires a GroupStyle with a HeaderTemplate to display grouping:
<ListBox x:Name="pictureBox" ItemsSource="{Binding Source={StaticResource photos}}">
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold"/>
</Border>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListBox.GroupStyle>
</ListBox>
π Definition β PropertyGroupDescription: An object that specifies which property to group by, optionally using a value converter to transform the grouping key.
π Example: A custom DateTimeToDateConverter converts DateTime values to "MM/dd/yyyy" format for grouping photos by date only, ignoring time:
view.GroupDescriptions.Add(new PropertyGroupDescription("datetime", new DateTimeToDateConverter()));
Filtering with Predicate
The Filter property accepts a Predicate<object> delegate. It is null by default. The example shows filtering to display only photos from the last 7 days using anonymous methods:
view.Filter = delegate(object o) {
return ((o as Photo).datetime - DateTime.Now).Days <= 7;
};
Alternative syntax using lambda expressions:
view.Filter = (o) => { return ((o as Photo).datetime - DateTime.Now).Days <= 7; };
π Definition β Filter: A property of type Predicate<object> that determines which items from the source collection are visible in the view.
Navigation with CurrentItem Management
Navigation refers to managing the current item within the collection view. The ICollectionView interface provides CurrentItem, CurrentPosition properties, and methods for changing them. The example shows previous/next button handlers with wrapping behavior:
void previous_Click(object sender, RoutedEventArgs e) {
ICollectionView view = CollectionViewSource.GetDefaultView(this.FindResource("photos"));
view.MoveCurrentToPrevious();
if (view.IsCurrentBeforeFirst) view.MoveCurrentToLast();
}
void next_Click(object sender, RoutedEventArgs e) {
ICollectionView view = CollectionViewSource.GetDefaultView(this.FindResource("photos"));
view.MoveCurrentToNext();
if (view.IsCurrentAfterLast) view.MoveCurrentToFirst();
}
Binding paths for navigation include:
"{Binding Path=/}" <!-- Current item -->
"{Binding Path=/datetime}" <!-- Current item's DateTime property -->
"{Binding Path=Photos/}" <!-- Current item of nested collection -->
"{Binding Path=Photos/datetime}" <!-- Current item's DateTime in nested collection -->
π Definition β CurrentItem: The item in the collection view that is tracked for navigation purposes, used in master/detail scenarios.
CollectionViewSource for Custom Views
CollectionViewSource can create new views that are applied to targets. It has its own SortDescriptions, GroupDescriptions properties, and a Filter event usable from XAML:
<CollectionViewSource x:Key="viewSource"
Filter="viewSource_Filter"
Source="{StaticResource photos}">
<CollectionViewSource.SortDescriptions>
<componentModel:SortDescription PropertyName="datetime" Direction="Descending"/>
</CollectionViewSource.SortDescriptions>
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="datetime"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
The event handler in code-behind:
void viewSource_Filter(object sender, FilterEventArgs e) {
e.Accepted = ((e.Item as Photo).datetime - DateTime.Now).Days <= 7;
}
π‘ Why this matters: IsSynchronizedWithCurrentItem is true by default for custom views created with CollectionViewSource, requiring explicit false setting, which differs from default views.
Data Providers in WPF
Data source objects can be arbitrary - databases, registry, Excel spreadsheets, etc. Two generic data-binding-friendly ways to expose common items are XmlDataProvider and ObjectDataProvider. Starting with WPF 3.5 SP1, data binding works with LINQ queries, providing an easier alternative to WPF data providers.
XmlDataProvider binds to inline XML or external XML files:
<Window.Resources>
<XmlDataProvider x:Key="dataProvider" xpath="gamestats">
<x:XData>
<gamestats xmlns="">
<gamestat Type="Beginner"><highscore>1203</highscore></gamestat>
<gamestat Type="Intermediate"><highscore>1089</highscore></gamestat>
<gamestat Type="Advanced"><highscore>541</highscore></gamestat>
</gamestats>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource dataProvider}, XPath=gamestat/highscore}"/>
</Grid>
π Definition β XmlDataProvider: A data provider that binds to XML documents, using XPath for path navigation instead of the Path property.
π Example: To access attributes, use XPath="gamestat/@Type" to populate the list with Type attribute values. External files use: <XmlDataProvider x:Key="dataProvider" xpath="gamestats" Source="gamestats.xml"/>
XML namespace pollution is avoided with xmlns="". Objects from System.Xml allow using Path and XPath together. Hierarchical binding to XML trees requires HierarchicalDataTemplate.
β Key Takeaways
Sorting must be applied before grouping, with the first sorting criterion matching the grouping criterion for meaningful output. Navigation through current item management works only when IsSynchronizedWithCurrentItem=true, otherwise SelectedItem and CurrentItem remain separate. CollectionViewSource provides full XAML-based view customization with its own SortDescriptions, GroupDescriptions, and Filter event. XmlDataProvider enables binding to XML data using XPath instead of Path, supporting both inline and external XML sources. Since WPF 3.5 SP1, LINQ queries can be used directly as binding sources, offering a cleaner alternative to traditional data providers for many scenarios.
π§ Quick Revision Questions
- What interface is implemented by the default view when IsSynchronizedWithCurrentItem is true?
- What is the method used to remove all sorting from a collection view?
- Which XAML element must be set on a ListBox for grouping to have a visual effect?
- What type is the Filter property on ICollectionView, and what does it return?
- What XAML attribute does XmlDataProvider use instead of Path for specifying data navigation?
π Lecture 31 β Hierarchical Data Templates, ObjectDataProvider, Binding Modes, Validation & RSS Reader
π Overview: This lecture covers advanced data binding techniques in WPF, including hierarchical data templates for XML data, the ObjectDataProvider for .NET objects, binding modes and triggers, validation rules, and the construction of a complete RSS reader application without code-behind. Understanding these concepts enables building sophisticated, data-driven user interfaces with minimal code.
ποΈ Topics Covered
The lecture begins with hierarchical data templates using XmlDataProvider for tree structures, then covers the ObjectDataProvider for declarative .NET object instantiation and method binding. It explains binding modes, update source triggers, and validation rules including custom validation, exception validation, and data error validation. Finally, it demonstrates building a complete RSS reader application using only XAML.
π Lecture Summary
Hierarchical Data Templates with XmlDataProvider
The lecture explains how to use HierarchicalDataTemplate to display XML data hierarchically in a TreeView. For each node type, a HierarchicalDataTemplate is defined, and for leaf nodes, a regular DataTemplate is used. The ItemsSource property on the template specifies children using {Binding xpath=*}. The DataType attribute corresponds to the XML node name and is used internally as a key, eliminating the need for an explicit key.
π Definition β HierarchicalDataTemplate: A WPF template that extends DataTemplate to allow specifying child items via the ItemsSource property, enabling hierarchical data display in TreeViews.
π Formula: <HierarchicalDataTemplate DataType="nodeName" ItemsSource="{Binding xpath=*}"> β This template applies to all XML nodes named "nodeName" and populates their children from all child XML elements.
π Example: For game stats XML:
<gamestats xmlns="">
<gamestat Type="Beginner">
<highscore>1203</highscore>
</gamestat>
</gamestats>
- Template for
gamestatsnode: displays italic "All Game Stats" - Template for
gamestatnode: displays bold 20pt text from@Typeattribute - Template for
highscoreleaf node: displays blue text from the inner text ({.})
ObjectDataProvider for .NET Objects
ObjectDataProvider wraps a .NET object as a data source, offering advantages over direct binding: declarative instantiation with parameterized constructors, method binding, and asynchronous data binding options. WPF provides two ways to mark async: the IsAsync property on Binding, and the IsAsynchronous property on XmlDataProvider and ObjectDataProvider (false by default for ObjectDataProvider, true by default for XmlDataProvider). When IsAsync is true, the source property is invoked on a background thread.
- π Definition β ObjectDataProvider: A WPF class that creates and uses a .NET object as a data source for binding, supporting constructor parameters and method binding.
- π Example β Wrapping a collection:
<Window.Resources>
<local:Photos x:Key="photos"/>
<ObjectDataProvider x:Key="dataprovider"
ObjectInstance="{StaticResource photos}"/>
</Window.Resources>
- π Example β Internal instantiation with constructor parameter:
<ObjectDataProvider x:Key="dataprovider"
ObjectType="{x:Type local:Photos}">
<ObjectDataProvider.ConstructorParameters>
<sys:Int32>23</sys:Int32>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
- π Example β Binding to a method:
<ObjectDataProvider x:Key="dataprovider"
ObjectType="{x:Type local:Photos}"
MethodName="getfoldername"/>
Binding Modes and Update Source Trigger
Binding.Mode determines the direction of data flow:
- OneWay: Target updates when source changes
- TwoWay: Both target and source update each other
- OneWayToSource: Source updates when target changes (opposite of OneWay)
- OneTime: Target receives a snapshot at binding initiation; source changes are not reflected
UpdateSourceTrigger controls when the source gets updated in TwoWay binding:
- PropertyChanged: Updates on every target property value change
- LostFocus: Updates when focus leaves the target element (default)
- Explicit: Requires calling
BindingExpression.UpdateSource()manually
π‘ Why this matters: TwoWay binding is default for editable controls like TextBox, requiring the ConvertBack method in value converters. Only OneWayToSource triggers ConvertBack.
Validation Rules
Validation provides immediate user feedback when invalid data is entered. Without binding, custom logic was needed, but binding automates data pushing to the target. Two approaches exist:
- Custom ValidationRule class β Derives from
ValidationRuleand overridesValidate()method - Source exceptions β Using
ExceptionValidationRuleorDataErrorValidationRule
π Definition β ValidationRule: A base class for creating custom validation logic that is executed whenever the binding attempts to update the target.
π Definition β ExceptionValidationRule: A built-in validation rule that catches exceptions thrown during source updates and shows them as validation errors.
π Definition β DataErrorValidationRule: A built-in validation rule that checks if the source implements IDataErrorInfo interface.
π Example β Custom JPG validation rule:
public class JpgValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string filename = value.ToString();
if (!File.Exists(filename))
return new ValidationResult(false, "Value is not a valid file.");
if (!filename.EndsWith(".jpg", StringComparison.InvariantCultureIgnoreCase))
return new ValidationResult(false, "Value is not a .jpg file.");
return new ValidationResult(true, null);
}
}
When validation fails, a default error adorner (thin red border) appears over the element, which can be customized via the Validation.ErrorTemplate attached property.
π Example β Setting validation in XAML:
<TextBox>
<TextBox.Text>
<Binding>
<Binding.ValidationRules>
<ExceptionValidationRule/>
<DataErrorValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Alternatively, using shortcuts: ValidatesOnExceptions="True" and ValidatesOnDataErrors="True".
Building an RSS Reader Without Code
The lecture demonstrates a complete RSS reader application using XmlDataProvider and master-detail binding. Key features include:
- A two-way TextBox for users to change the feed address, using
BindsDirectlyToSource="True"so the path doesn't refer to the RSS feed - UpdateSourceTrigger="PropertyChanged" to update on every keystroke
- A ListBox and Frame sharing the same data source for master-detail display
π Example β RSS Reader XAML:
<Window.Resources>
<XmlDataProvider x:Key="Feed"
Source="http://twitter.com/statuses/user_timeline/24326956.rss"/>
</Window.Resources>
<DockPanel DataContext="{Binding Source={StaticResource Feed}, XPath=/rss/channel/item}">
<TextBox DockPanel.Dock="Top"
Text="{Binding Source={StaticResource Feed},
BindsDirectlyToSource=true, Path=Source,
UpdateSourceTrigger=PropertyChanged}"/>
<Label DockPanel.Dock="Top"
Content="{Binding XPath=/rss/channel/title}"
FontSize="14" FontWeight="Bold"/>
<Label DockPanel.Dock="Top"
Content="{Binding XPath=/rss/channel/description}"/>
<ListBox DockPanel.Dock="Left" DisplayMemberPath="title"
ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True" Width="300"/>
<Frame Source="{Binding XPath=link}"/>
</DockPanel>
β Key Takeaways
The most critical concepts from this lecture are: (1) HierarchicalDataTemplate enables displaying XML hierarchies in TreeViews by specifying children through ItemsSource with XPath binding and using DataType as the template key; (2) ObjectDataProvider allows declarative instantiation of .NET objects with constructor parameters and method binding, plus async support through IsAsynchronous property; (3) Binding modes (OneWay, TwoWay, OneWayToSource, OneTime) control data flow direction, while UpdateSourceTrigger (PropertyChanged, LostFocus, Explicit) controls when the source is updated; (4) Validation can be implemented through custom ValidationRule classes or built-in ExceptionValidationRule/DataErrorValidationRule, with automatic error adorner display on validation failure; (5) A complete RSS reader can be built without code-behind using XmlDataProvider, master-detail binding with IsSynchronizedWithCurrentItem, and BindsDirectlyToSource for text box feed URL editing.
π§ Quick Revision Questions
- What is the difference between HierarchicalDataTemplate and regular DataTemplate, and how does the DataType attribute work with XML nodes?
- List the four binding modes and explain the data flow direction for each, including which mode requires a ConvertBack method.
- What are the three values of UpdateSourceTrigger, and when does each update the source in TwoWay binding?
- How do you create a custom validation rule, and what happens visually when validation fails in a bound TextBox?
- Explain how the RSS reader example achieves master-detail binding between the ListBox and Frame without any code-behind.
π Lecture 32 β Concurrency and Threading
π Overview: This lecture introduces the concept of concurrency and threading in C#. It explains how to create and manage threads, handle shared and local state, ensure thread safety using locks, pass data to threads, and signal between threads. Understanding threading is crucial for building responsive and efficient applications.
ποΈ Topics Covered
The lecture covers the definition of concurrency and its comparison with events, the concept of threads and multithreading, creating and starting threads with the Thread class, thread life cycle methods like Join and Sleep, local versus shared state, thread safety and the lock statement, passing data to threads using lambda expressions and ParameterizedThreadStart, the issue of captured variables in loops, exception handling in threads, and signaling between threads using ManualResetEvent.
π Lecture Summary
Concurrency and Threading Basics
Concurrency means more than one thing happening at the same time. It is needed for responsive user interfaces, simultaneous requests, and parallel programming. An event is a notification that something happened in the same thread, whereas concurrency uses separate threads. A thread is an execution path that can proceed independently of others. Normal processes (programs in execution) have one thread. Multithreaded programs have more than one thread and can share data.
π Definition β Thread: An execution path that can proceed independently of others within a process.
Creating a Thread
To create a thread, instantiate a Thread object and pass a method to its constructor, then call Start(). The main thread and the new thread run concurrently.
π Example:
class threadtest {
static void Main() {
Thread t = new Thread(writey);
t.Start();
for (int i = 0; i < 1000; i++) Console.Write("x");
}
static void writey() {
for (int i = 0; i < 1000; i++) Console.Write("y");
}
}
Typical Output: xxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxx
Output is interleaved due to time slicing (the OS gives each thread small time slices). On multicore, real parallelism occurs, but repeated blocks appear due to how Console handles output.
Thread Properties and Methods
IsAlive:trueonce the thread starts and until it ends.Name: A property to name a thread for debugging.Thread.CurrentThread: Returns the currently executing thread.Join(): Blocks the calling thread until the target thread finishes.Sleep(): Blocks the current thread for a specified time.
π Definition β Blocked: A thread is blocked when it is waiting (e.g., via Join, Sleep). Use the ThreadState property to check.
π Example of Join:
static void Main() {
Thread t = new Thread(Go);
t.Start();
t.Join(); // Main waits for t to finish
Console.WriteLine("Thread t has ended!");
}
static void Go() { for (int i = 0; i < 1000; i++) Console.Write("y"); }
π Example of Sleep:
Thread.Sleep(TimeSpan.FromHours(1)); // Sleep for 1 hour
Thread.Sleep(500); // Sleep for 500 milliseconds
Local vs Shared State
Each thread has its own local state (method-level variables). When multiple threads access shared state (e.g., instance or static fields), issues arise.
π Local State Example:
static void Main() {
new Thread(Go).Start();
Go();
}
static void Go() {
for (int cycles = 0; cycles < 5; cycles++) Console.Write('?');
}
// Output: '??????????' (each thread has its own 'cycles')
π Shared State Example (instance field):
class threadtest {
bool _done;
static void Main() {
threadtest tt = new threadtest();
new Thread(tt.Go).Start();
tt.Go();
}
void Go() {
if (!_done) { _done = true; Console.WriteLine("Done"); }
}
}
Both threads can read _done as false and both may write "Done". This is a race condition.
π Shared State Example (static field):
class threadtest {
static bool _done;
static void Main() {
new Thread(Go).Start();
Go();
}
static void Go() {
if (!_done) { _done = true; Console.WriteLine("Done"); }
}
}
Same problem β can output "Done" twice.
Thread Safety with lock
To prevent race conditions, use the lock statement. It ensures that only one thread can execute the critical section at a time.
π Definition β Thread Safety: Code that works correctly when accessed by multiple threads simultaneously.
π Example:
class threadsafe {
static bool _done;
static readonly object _locker = new object();
static void Main() {
new Thread(Go).Start();
Go();
}
static void Go() {
lock (_locker) {
if (!_done) { Console.WriteLine("Done"); _done = true; }
}
}
}
Now "Done" is output exactly once because the lock ensures mutual exclusion.
Passing Data to Threads
Two ways to pass data: using a lambda expression (easiest) or using ParameterizedThreadStart.
π Definition β Lambda Expression: An anonymous function that can contain expressions and statements.
π Using Lambda:
static void Main() {
Thread t = new Thread(() => Print("Hello from t!"));
t.Start();
}
static void Print(string message) { Console.WriteLine(message); }
π Lambda with multiple statements:
new Thread(() => {
Console.WriteLine("I'm running on another thread!");
Console.WriteLine("This is so easy!");
}).Start();
π Using ParameterizedThreadStart:
static void Main() {
Thread t = new Thread(Print);
t.Start("Hello from t!");
}
static void Print(object messageObj) {
string message = (string)messageObj;
Console.WriteLine(message);
}
π Definition β Delegates:
ThreadStart: Delegate for methods that take no arguments.ParameterizedThreadStart: Delegate for methods that take oneobjectargument.
Lambda Expressions and Captured Variables
Capturing a loop variable in a lambda causes all threads to share the same variable.
π Problem Example:
for (int i = 0; i < 10; i++)
new Thread(() => Console.Write(i)).Start();
// Typical Output: 0223557799 (unpredictable)
π Solution β Use a temporary variable:
for (int i = 0; i < 10; i++) {
int temp = i;
new Thread(() => Console.Write(temp)).Start();
}
// Output: 0123456789 (more predictable)
Exception Handling in Threads
An exception thrown in a thread cannot be caught in the calling thread. Each thread must handle its own exceptions.
π Wrong Way:
public static void Main() {
try {
new Thread(Go).Start();
}
catch (Exception ex) {
Console.WriteLine("Exception!"); // This never runs
}
}
static void Go() { throw null; }
π Correct Way:
public static void Main() {
new Thread(Go).Start();
}
static void Go() {
try {
// ...
throw null;
// ...
}
catch (Exception ex) {
// Handle exception within the thread
}
}
Thread Properties: Background and Priority
IsBackground: Iftrue, the thread does not keep the application alive. The process exits when all foreground threads end.Priority: Determines how much CPU time the thread gets relative to others.
Signaling Between Threads with ManualResetEvent
A ManualResetEvent is the simplest signaling mechanism.
π Definition β ManualResetEvent: A synchronization primitive that allows one thread to signal another.
π Definition β WaitOne(): Blocks the current thread until the signal is set. π Definition β Set(): Sends the signal, unblocking the waiting thread. π Definition β Reset(): Closes the signal (makes it unsignaled again).
π Example:
var signal = new ManualResetEvent(false);
new Thread(() => {
Console.WriteLine("Waiting for signal...");
signal.WaitOne();
signal.Dispose();
Console.WriteLine("Got signal!");
}).Start();
Thread.Sleep(2000);
signal.Set();
The child thread waits until the main thread calls signal.Set() after 2 seconds.
π‘ Why this matters: ManualResetEvent provides a simple way to coordinate threads without busy waiting.
β Key Takeaways
Threading allows multiple execution paths within a single process, enabling responsive UIs and parallel processing. Use lock with a dedicated object to ensure thread safety when accessing shared state. Always handle exceptions inside the thread body, as they cannot propagate to the creating thread. Pass data to threads most easily via lambda expressions, and be careful with captured loop variables by using a temporary copy. Use ManualResetEvent with WaitOne() and Set() for simple thread signaling.
π§ Quick Revision Questions
- What is the difference between concurrency and events?
- How do you create and start a thread in C#?
- What does the
lockstatement do and why is it important for thread safety? - Why can't exceptions thrown in a thread be caught in the calling thread?
- What is the purpose of
ManualResetEventand how doWaitOne()andSet()work?