我想用 ItemsSource 属性创建一个自己的用户控件。我创建了一个用户控件“myContainer”,并创建了一个用户控件“myItem”。现在我想在 myContainer 控件中显示 myItem 控件。所以我在 myContainer 控件中声明了一个依赖属性 ItemsSource。但是,如果我启动一个 testproject 并将一个集合绑定到 itemssource 属性,则什么也没有发生。这是实现 itemssource 属性的正确方法吗?
Xaml:我的容器
<UserControl x:Class="Control.myContainer"
...
x:Name="myUserControl">
<Grid>
<DockPanel x:Name="myDockPanel">
</DockPanel>
</Grid>
myContainer 背后的代码
public partial class myContainer : UserControl, INotifyPropertyChanged
{
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(myItem), typeof(myContainer));
public myContainer()
{
InitializeComponent();
DataContext = this;
}
public ObservableCollection<myItem> ItemsSource
{
get
{
return (ObservableCollection<myItem>)GetValue(ItemsSourceProperty);
}
set
{
SetValue(ItemsSourceProperty, value);
OnPropertyChanged("ItemsSource");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Xaml 我的项目
<UserControl x:Class="Control.myItem"
...
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Border BorderThickness="1" BorderBrush="Black" CornerRadius="2">
<DockPanel>
<StackPanel DockPanel.Dock="Top" Background="LightGray">
<DockPanel Margin="2,2,2,2">
<Button x:Name="Button_Close" DockPanel.Dock="Right" Width="14" Height="14" Margin="5,0,0,0" VerticalAlignment="Center"></Button>
<Button x:Name="Button_Undock" DockPanel.Dock="Right" Width="14" Height="14" Margin="5,0,0,0" VerticalAlignment="Center"></Button>
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" FontWeight="Bold" Text="{Binding Header,UpdateSourceTrigger=PropertyChanged}"></TextBlock>
</DockPanel>
</StackPanel>
<ContentPresenter DockPanel.Dock="Top" ContentSource="Content"></ContentPresenter>
</DockPanel>
</Border>
</Grid>
我的项目背后的代码
public partial class myItem : UserControl, INotifyPropertyChanged
{
public static DependencyProperty _Header =
DependencyProperty.Register("Header", typeof(String), typeof(myItem), new UIPropertyMetadata("Item"));
public myItem()
{
InitializeComponent();
DataContext = this;
}
public String Header
{
get
{
return (String)GetValue(_Header);
}
set
{
SetValue(_Header, value);
OnPropertyChanged("Header");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}