I have got an exception "Cannot find resource named 'mrg'. Resource names are case sensitive." when I try to do the following:
MainWindow.xaml:
<Window.Resources>
<Thickness Left="0"
Right="1"
Bottom="2"
Top="3"
x:Key="mrg" />
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:UserControl1 />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<string> source = new List<string>()
{
"item1",
"item2",
"item3",
"item4",
"item5",
};
DataContext = source;
}
}
and UserControl1.xaml:
<Grid>
<TextBlock Text="{Binding}" Margin="{StaticResource mrg}" />
</Grid>
According to the msdn article:
Static resource lookup behavior
The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.
The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.
Next, application resources are checked. Application resources are those resources within the resource dictionary that is defined by the Application object for your WPF application.
So the resource had to be found because of step 2. But, as I can see in the Locals
window when exception is catched, the UserControl1.Parent == null
.
I'm confused in this problem. The way I can solve it is to put the resource to the Application level.
My question is: why the StaticResource connot be found ?