多个用户控件共享集合依赖项属性

时间:2010-07-09 16:54:41

标签: wpf dependency-properties itemscontrol

我已根据列表框实现了自己的usercontrol。它具有一个具有集合类型的依赖项属性。当我在一个窗口中只有一个usercontrol实例时它工作正常,但如果我有多个实例,我会遇到问题,他们共享集合依赖属性。以下是说明这一点的示例。

我的用户控件名为SimpleList:

<UserControl x:Class="ItemsTest.SimpleList"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Name="_simpleList">
    <StackPanel>
        <TextBlock Text="{Binding Path=Title, ElementName=_simpleList}" />
        <ListBox 
            ItemsSource="{Binding Path=Numbers, ElementName=_simpleList}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </StackPanel>    
</UserControl>

代码背后:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace ItemsTest
{
    public partial class SimpleList : UserControl
    {
        public SimpleList()
        {
            InitializeComponent();
        }

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string), typeof(SimpleList), new UIPropertyMetadata(""));


        public List<int> Numbers 
        {
            get { return (List<int> )GetValue(NumbersProperty); }
            set { SetValue(NumbersProperty, value); }
        }

        public static readonly DependencyProperty NumbersProperty =
            DependencyProperty.Register("Numbers ", typeof(List<int>), typeof(SimpleList), new UIPropertyMetadata(new List<int>()));
    }
}

我这样用:

   <StackPanel>
        <ItemsTest:SimpleList Title="First">
            <ItemsTest:SimpleList.Numbers>
                <sys:Int32>1</sys:Int32>
                <sys:Int32>2</sys:Int32>
                <sys:Int32>3</sys:Int32>
            </ItemsTest:SimpleList.Numbers>
        </ItemsTest:SimpleList>
        <ItemsTest:SimpleList Title="Second">
            <ItemsTest:SimpleList.Numbers>
                <sys:Int32>4</sys:Int32>
                <sys:Int32>5</sys:Int32>
                <sys:Int32>6</sys:Int32>
            </ItemsTest:SimpleList.Numbers>
        </ItemsTest:SimpleList>
    </StackPanel>

我希望以下内容显示在我的窗口中:

First
123
Second
456

但我看到的是:

First
123456
Second
123456

如何让多个SimpleList不共享他们的Numbers Collection ???

1 个答案:

答案 0 :(得分:18)

找到答案,构造函数需要初始化属性而不是让静态属性自行执行:

public SimpleList()
{
   SetValue(NumbersProperty, new List<int>()); 

   InitializeComponent();
}

Collection-Type Dependency Properties