如何两次使用一个资源?
在我的应用程序资源中,我有:
<Application.Resources>
<Border x:Key="border1" BorderBrush="{x:Null}" BorderThickness="0" Height="159" Width="5" >
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFFC0C0C" Offset="0" />
<GradientStop Color="#63FF0000" Offset="0.999" />
<GradientStop Color="#6AFE0000" Offset="0.048" />
</LinearGradientBrush>
</Border.Background>
</Border>
</Application.Resources>
我想将该边框添加到堆栈面板中,例如:
Border temp = new Border();
temp = (Border)FindResource("border1");
temp.Name = "bar" + i;
stackPanel1.Children.Add(temp);
这工作正常。唯一的问题是我想添加该边框的两个实例。因此,我将其放在循环中:
for (int i = 0; i < 10; i++)
{
Border temp = new Border();
temp = (Border)FindResource("border1");
temp.Name = "bar" + i;
stackPanel1.Children.Add(temp);
}
在第二次迭代中,我收到错误:
但对我来说似乎不是解析异常,因为请注意第一次迭代没有问题:
怎么可能我多次使用同一个资源?我知道我可以动态创建该资源,但我需要实际使用该资源。
In my application resources I have:
<Application.Resources>
<Border x:Key="border1" BorderBrush="{x:Null}" BorderThickness="0" Height="159" Width="5" >
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFFC0C0C" Offset="0" />
<GradientStop Color="#63FF0000" Offset="0.999" />
<GradientStop Color="#6AFE0000" Offset="0.048" />
</LinearGradientBrush>
</Border.Background>
</Border>
</Application.Resources>
I will like to add that border to a stack panel like:
Border temp = new Border();
temp = (Border)FindResource("border1");
temp.Name = "bar" + i;
stackPanel1.Children.Add(temp);
This works fine. The only problem is that I would like to add two instances of that border. Therefore I have placed that inside a loop:
for (int i = 0; i < 10; i++)
{
Border temp = new Border();
temp = (Border)FindResource("border1");
temp.Name = "bar" + i;
stackPanel1.Children.Add(temp);
}
on the second iteration I get the error:
But to me there does not seem to be a parse exeption because note how there is no problem on the first iteration:
How could I use a resource several times? I know I could create that resource dynamically but I need to actually use the resource.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您将 x:Shared="false" 添加到资源定义中,它应该起作用:
If you add x:Shared="false" to your resource definition, it should work: