我需要制作Usercontrol
并在我使用它的Window
中添加它的控件,因此我在其中定义了ItemsControl
,如下所示:
<UserControl x:Class="MySystem.Controls.DropDownPanel"
x:Name="this" ....>
<Grid>
<Popup x:Name="popup" ...>
<Grid>
<ItemsControl ItemsControl.ItemsSource="{Binding ElementName=this, Path=PanelItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
</Popup>
</Grid>
我还在后面的代码中创建了一个DependencyProprty
(PanelsItem):
public static readonly DependencyProperty PanelItemsProperty = DependencyProperty.Register("PanelItems"
, typeof(ObservableCollection<UIElement>)
, typeof(DropDownPanel));
public ObservableCollection<UIElement> PanelItems
{
get
{
return (ObservableCollection<UIElement>)GetValue(PanelItemsProperty);
}
set
{
SetValue(PanelItemsProperty, value);
}
}
现在我想添加如下控件:
<Windowx:Class="MySystem.UI.View.PeopleView"
...
x:Name="this"
xmlns:controls="clr-namespace:MySystem.Controls;assembly=MySystem.Controls">
<Grid>
<controls:DropDownPanel>
<commonControls:DropDownPanel.PanelItems>
//??How to add controls Here??
</commonControls:DropDownPanel.PanelItems>
</commonControls:DropDownPanel>
</Grid>
</Window>
如果我直接在PanelsItem
添加控件,我会收到此错误:
{“'Collection属性'MySystem.Controls.DropDownPanel'。'PanelItems'为null'”}
任何想法?
答案 0 :(得分:0)
要解决错误{“'Collection属性'MySystem.Controls.DropDownPanel'。'PanelItems'为null'”}只需为依赖项属性添加默认值。替换:
public static readonly DependencyProperty PanelItemsProperty = DependencyProperty.Register("PanelItems"
, typeof(ObservableCollection<UIElement>)
, typeof(DropDownPanel));
为:
public static readonly DependencyProperty PanelItemsProperty = DependencyProperty.Register("PanelItems"
, typeof(ObservableCollection<UIElement>)
, typeof(DropDownPanel)
, new PropertyMetadata(new ObservableCollection<UIElement>()));
修改强>
项目已添加到PanelItems
,但不会与ItemsControl
绑定。而不是:
<ItemsControl ItemsControl.ItemsSource="{Binding ElementName=this, Path=PanelItems}">
使用:
<ItemsControl ItemsControl.ItemsSource="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType=UserControl, Mode=FindAncestor}, Path=PanelItems}">
此外,您对Popup
使用ItemsControl
控件。因此,如果要查看添加的项目,则必须将IsOpen
属性Popup
设置为true。完成后,您将能够这样做:
<controls:DropDownPanel DataContext="{Binding DataContext, ElementName=this}">
<commonControls:DropDownPanel.PanelItems>
<TextBlock Text="some text" Width="100" Height="25" />
</commonControls:DropDownPanel.PanelItems>
</commonControls:DropDownPanel>
此处不需要BTW DataContext="{Binding DataContext, ElementName=this}"
。您只需将DataContext
绑定到自身。