【问题标题】:Items in CustomControl WpfCustomControl Wpf 中的项目
【发布时间】:2012-10-28 09:07:13
【问题描述】:

我有一个自定义控件


    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>()));        

当我在我的应用程序中使用多个 CustomControl1 并为每个 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>

运行解决方案时,每个 CustomControl1 中显示的所有值 并且在设计模式下只显示最后一个 customcontrol1 的值。

所以看起来它们都共享相同的实例数据。

【问题讨论】:

  • 我想在第一个控件中设置一个像这样的列表 [A,B,C,D] 并在第二个控件中设置像 [E,F] 这样的列表但是当运行这个每个控件时显示 [A,B ,C,D,E,F] 并且在设计模式下只显示 [E,F] ???!

标签: wpf custom-controls items


【解决方案1】:

为集合(列表、字典……)创建依赖属性时始终在类的构造函数中重新初始化 DP。 (否则,您将对所有实例使用相同的列表)

所以在你的情况下:

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

并删除依赖属性默认值中的值:

public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(List<string>), 
                                                   typeof(CustomControl1), 
                                                   new UIPropertyMetadata(null));        

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多