Wal*_*mer 12 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>
Run Code Online (Sandbox Code Playgroud)
代码背后:
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>()));
}
}
Run Code Online (Sandbox Code Playgroud)
我用这样的:
<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>
Run Code Online (Sandbox Code Playgroud)
我希望以下内容显示在我的窗口中:
First
123
Second
456
Run Code Online (Sandbox Code Playgroud)
但我看到的是:
First
123456
Second
123456
Run Code Online (Sandbox Code Playgroud)
如何让多个SimpleList不共享他们的Numbers Collection ???
Wal*_*mer 18
找到答案,构造函数需要初始化属性而不是让静态属性自行执行:
public SimpleList()
{
SetValue(NumbersProperty, new List<int>());
InitializeComponent();
}
Run Code Online (Sandbox Code Playgroud)