我有一个异常(exception) “找不到名为‘mrg’的资源。资源名称区分大小写。” 当我尝试执行以下操作时:
主窗口.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>
主窗口.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<string> source = new List<string>()
{
"item1",
"item2",
"item3",
"item4",
"item5",
};
DataContext = source;
}
}
和 UserControl1.xaml:
<Grid>
<TextBlock Text="{Binding}" Margin="{StaticResource mrg}" />
</Grid>
根据msdn article :
静态资源查找行为
因此,由于第 2 步,必须找到资源。但是,正如我在
Locals
中看到的那样捕获异常时的窗口,UserControl1.Parent == null
.我对这个问题感到困惑。我可以解决的方法是将资源放到应用程序级别。
我的问题是:为什么找不到 StaticResource ?
最佳答案
DataTemplate 形成了自己的逻辑树,它与 ItemsControl 的逻辑树是断开的。因此,遍历逻辑树的查找将找不到资源。
我无法在 MSDN 中找到引用,只有 this article on CodeProject ,它写道:
The elements that are part of an expanded template, hereafter referred to as "template elements", form their own logical tree which is disconnected from the logical tree of the object for which they were created.
使用
DynamicResource
而不是 StaticResource
将克服这个问题。但是我不能确切地说出原因。也许可以在 Static and Dynamic Resources 中的静态资源查找行为和动态资源查找行为部分找到解释。 ,但我不确定。
关于wpf - 为什么在这种情况下无法解析 StaticResource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14454672/