[英]Defining StackPanel resources programmatically?
I'm just poking around some WPF samples I found online, and came across an odd behaviour which I have simplified it below: 我只是在寻找我在网上发现的一些WPF样本,并且遇到了一个奇怪的行为,我在下面简化了它:
<StackPanel Name="sp1">
<StackPanel.Resources>
<!--<src:ItemsForSale x:Key="MyData"/>-->
</StackPanel.Resources>
<ListView Name="itemsControl" ItemsSource="{StaticResource MyData}">
<ListView.View>
</ListView.View>
</ListView>
</StackPanel>
If I un-comment line 3 (the resource definition) everything works great. 如果我取消评论第3行(资源定义),一切都很好。 However, if I comment that line out, and programmatically add the following:
但是,如果我对该行进行注释,并以编程方式添加以下内容:
public MainWindow()
{
InitializeComponent();
sp1.Resources.Add("MyData", new ItemsForSale());
}
I get the runtime exception A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
我得到运行时异常
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
I've tried adding the resource in the stackpanel's Loaded
and Initialized
event to no avail. 我尝试在stackpanel的
Loaded
和Initialized
事件中添加资源无济于事。
To sum up comments problem was caused by control that required MyData
resource during initialization and threw this exception: 总结注释问题是由初始化期间需要
MyData
资源的控件引起的,并引发了此异常:
Cannot find resource named 'MyData'.
找不到名为“MyData”的资源。 Resource names are case sensitive
资源名称区分大小写
To solve the problem instead of StaticResource
use DynamicResource
要解决问题而不是
StaticResource
使用DynamicResource
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.