It's actually easy.
Declare the attached property with Inherits
-option:
public static string GetFoo(DependencyObject obj)
{
return (string)obj.GetValue(FooProperty);
}
public static void SetFoo(DependencyObject obj, string value)
{
obj.SetValue(FooProperty, value);
}
public static readonly DependencyProperty FooProperty =
DependencyProperty.RegisterAttached(
"Foo", typeof(string), typeof(MainWindow),
new FrameworkPropertyMetadata(
"default",
// this bit is important:
FrameworkPropertyMetadataOptions.Inherits));
Test XAML:
<Grid src:MainWindow.Foo="non-default">
<TextBlock Text="{Binding (src:MainWindow.Foo),
RelativeSource={RelativeSource Self}}"/>
</Grid>
shows "nondefault".
This works across template boundary as well, full example follows.
<Window x:Class="DPInheritance.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:DPInheritance"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="Test">
<TextBlock Text="{Binding (src:MainWindow.Foo),
RelativeSource={RelativeSource Self}}"/>
</DataTemplate>
</Window.Resources>
<Grid src:MainWindow.Foo="non-default">
<ItemsControl ItemTemplate="{StaticResource Test}">
<sys:Int32>0</sys:Int32>
<sys:Int32>1</sys:Int32>
<sys:Int32>2</sys:Int32>
</ItemsControl>
</Grid>
</Window>