我有一个自定义的用户控件,其中包含列表和按钮:
<UserControl x:Class="WpfApplication1.CustomList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ListBox Name="listBox1" ItemsSource="{Binding ListSource}" HorizontalAlignment="Right" Width="174" />
<Button Name="ButtonAdd" Content="Add" HorizontalAlignment="Left" Width="101" />
</Grid>
</UserControl>
代码后面有一个类型为IEnumerable的DependencyProperty和一个Button的处理程序(OnAdd):
public partial class CustomList : UserControl
{
public CustomList( )
{
InitializeComponent( );
ButtonAdd.Click += new RoutedEventHandler( OnAdd );
}
private void OnAdd( object sender, EventArgs e )
{
IList<object> tmpList = this.ListSource.ToList( );
Article tmpArticle = new Article( );
tmpArticle .Name = "g";
tmpList.Add(tmpArticle );
ListSource = (IEnumerable<object>) tmpList;
}
public IEnumerable<object> ListSource
{
get
{
return (IEnumerable<object>)GetValue( ListSourceProperty );
}
set
{
base.SetValue(CustomList.ListSourceProperty, value);
}
}
public static DependencyProperty ListSourceProperty = DependencyProperty.Register(
"ListSource",
typeof( IEnumerable<object> ),
typeof( CustomList ),
new PropertyMetadata( OnValueChanged ) );
private static void OnValueChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
( (CustomList)d ).ListSource = (IEnumerable<object>)e.NewValue;
}
}
在按钮处理程序中,我正在尝试将文章添加到ListSource(它绑定到Articles)。这是我使用自定义用户控件(CustomList)的窗口:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:CustomList ListSource="{Binding Articles, Mode=TwoWay}" Margin="80,0,0,0" />
</Grid>
</Window>
当我点击按钮时,文章会变成null,而不是将文章添加到文章集合中。ListSource属性也变为null。我在这里做错了什么吗?这是预期的行为吗?如果是,有没有其他不同的方法可以实现: 创建一个自定义控件,该控件将具有列表和按钮,按钮的处理程序将向列表中添加对象。