【问题标题】:Multiple instances of a UserControl with DependencyProperty具有 DependencyProperty 的 UserControl 的多个实例
【发布时间】: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# 代码才能确定发生了什么。

标签: c# xaml


【解决方案1】:

问题是由实例变量引起的。通过删除实例变量并修改 PropertyChangedCallback 方法中的 ShadowRec 和 DataRec,问题得到解决。对于以后遇到类似问题的任何人,它应该看起来像这样:

    private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        GraphBar gb = sender as GraphBar;
        // do something here, such as: gb.DataRec.Width = 15;
    }

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 2016-04-21
    • 2014-05-03
    • 2011-06-29
    • 1970-01-01
    • 2012-03-02
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多