0

我需要制作一个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 property 'MySystem.Controls.DropDownPanel'.'PanelItems' is null'”}

有任何想法吗?

4

1 回答 1

0

要解决错误 {"'Collection property 'MySystem.Controls.DropDownPanel'.'PanelItems' is 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>

顺便说一句DataContext="{Binding DataContext, ElementName=this}",这里不需要。你只是绑定DataContext到它自己。

于 2013-05-25T08:29:38.777 回答