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

2024-01-29

我已经实现了自己的基于列表框的用户控件。它具有集合类型的依赖属性。当我在窗口中只有一个用户控件实例时,它工作得很好,但如果我有多个实例,我会遇到它们共享集合依赖属性的问题。下面是一个示例来说明这一点。

我的用户控件称为 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 集合???


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

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

   InitializeComponent();
}

集合类型依赖属性 http://msdn.microsoft.com/en-us/library/aa970563.aspx

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

多个用户控件共享集合依赖属性 的相关文章

随机推荐