【发布时间】:2015-03-13 15:26:45
【问题描述】:
我创建了一个UserControl,它使用了多个DependencyProperties。当我只有一个 UserControl 实例时,一切都按预期工作。但是,如果我创建对象的多个实例,则只有第一个实例有效(注意:不会引发错误)。我唯一能想到的是不可能有多个DependencyProperty 实例。这个对吗?如果是这样,是否有任何替代方案/解决方法?
这是我设置 DependencyProperties 的方式示例:
public int Value
{
get { return (int)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static DependencyProperty ValueProperty=
DependencyProperty.Register("Value", typeof(int), typeof(DataBar), new PropertyMetadata(0));
用户控件的 XML:
x:Name="DataBarUserControl">
<Grid>
<Rectangle Name="BackgroundRec" Height="{Binding Height, ElementName=DataBarUserControl}" Width="{Binding Width, ElementName=DataBarUserControl}"
Fill="{Binding BarBackground, ElementName=DataBarUserControl}" HorizontalAlignment="Stretch"
VerticalAlignment="Top">
</Rectangle>
<Rectangle Name="ShadowRec" Height="{Binding Height, ElementName=DataBarUserControl}" Fill="{Binding BarBackground, ElementName=DataBarUserControl}"
HorizontalAlignment="Left" Opacity="0.25"
Stroke="{Binding BarBackground, ElementName=DataBarUserControl}">
</Rectangle>
<Rectangle Name="DataRec" Height="{Binding Height, ElementName=DataBarUserControl}" Fill="{Binding BarForeground, ElementName=DataBarUserControl}"
HorizontalAlignment="Left">
</Rectangle>
</Grid>
ShadowRec & DataRec 根本不显示。
更新 1:
我想我已经找到了问题的根本原因。在 UserControl 的后端,我修改了存储为私有静态变量的 ShadowRec 和 DataRec。当我禁用这部分代码时,问题就消失了。不确定是否抓取了错误的实例,或者是否有更具体的方式我应该存储实例。
【问题讨论】:
-
您好,请将您的 xaml 发布到用户控件所在的位置。
-
发布了 XAML,其中包含有关该问题的更多详细信息。
-
ShadowRec 和 DataRec 在 BackgroundRec 后面。将矩形放在 StackPanel 中,您将看到它们。
-
@dellywheel:实际上,它们的分层是正确的:ShadowRec 在 BackgroundRec 上,DataRec 在 ShadowRec 上。如前所述,这可以按预期工作,但只是 UserControl 的第一个实例。我什至测试过禁用除 DataRec 之外的所有功能,但问题仍然存在。如更新 1 中所述,这似乎是实例问题,而不是放置问题。
-
啊,我明白了。在用户控件上使用静态变量(而不是依赖属性)可能会导致各种问题。可能必须查看用户控件的所有 C# 代码才能确定发生了什么。