i have a customcontrol


    static CustomControl1()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new     FrameworkPropertyMetadata(typeof(CustomControl1)));
    }

    public List<string> MyProperty
    {
        get { return (List<string>)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(List<string>), 
                                                   typeof(CustomControl1), 
                                                   new UIPropertyMetadata(new List<string>()));        

When I use more than one of the CustomControl1 in my application and set value for each MyProperty

  <StackPanel HorizontalAlignment="Left" Orientation="Vertical" VerticalAlignment="Top" Width="176">
        <local:CustomControl1>          
            <local:CustomControl1.MyProperty>
                <System:String>A</System:String>
                <System:String>B</System:String>
                <System:String>C</System:String>
                <System:String>D</System:String>
            </local:CustomControl1.MyProperty>          
        </local:CustomControl1>
        <local:CustomControl1>          
            <local:CustomControl1.MyProperty>
                <System:String>F</System:String>
                <System:String>E</System:String>                    
            </local:CustomControl1.MyProperty>          
        </local:CustomControl1>
    </StackPanel>

when run solution , all values shown in each CustomControl1 and in design mode only show value of last customcontrol1.

So it looks as all of them share the same instance data.

有帮助吗?

解决方案

When creating a Dependency Property for a collection (List, Dictionary…) always reinitialize the DP in the class’s constructor. (Otherwise you’ll be using the same list for all instances)

So in your case:

public CustomControl1()
{
    MyProperty = new List<string>();
}

and remove the value in the Dependency Property's default value:

public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(List<string>), 
                                                   typeof(CustomControl1), 
                                                   new UIPropertyMetadata(null));        
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top