簡體   English   中英

C#WPF:將自定義用戶控件添加到Stackpanel

[英]C# WPF: Adding custom Usercontrol to Stackpanel

我嘗試了一些有關將我自己創建的用戶控件元素添加到列表框或堆棧面板的操作,但未獲得任何成功,而是導致了NullReferenceException ,我不知道為什么...

我的用戶控件看起來像這樣:

public partial class ShiftInformationItem : UserControl
{
    public ShiftInformationItem()
    {
        InitializeComponent();
    }
}

和xaml:

<Grid>
    <LabelContent="Benutzername:" />
    <Label Content="01.03.2014 14:19" />
    <TextBox Text="Eintrag ..." />
    <Expander Header="Comments (0)">
        <Grid Background="#FFE5E5E5"/>
    </Expander>
</Grid>

在主窗口中,我可以將其添加到列表框或堆棧面板中,而不會出現任何麻煩:

<ListBox>
     <controls:ShiftInformationItem  />
</ListBox>

要么:

<StackPanel Name="ShiftInformationPanel">
     <controls:ShiftInformationItem  />
</StackPanel>

但是當我嘗試使用C#添加它時:

ShiftInformationList.Items.Add(new ShiftInformationItem());
ShiftInformationPanel.Children.Add(new ShiftInformationItem());

它導致NullReferenceException並說我要添加的對象為null。

有人能解釋我為什么嗎?

我非常感謝所有預先提供的有益和有益的答案!

更新:

public partial class HoBusReceptionMain : Window
{
    public HoBusReceptionMain()
    {
        InitializeComponent();
    }

    private void RibbonWin_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        RibbonTab r = (RibbonTab)e.AddedItems[0];
        switch (r.Header.ToString())
        {
            case "Shift Information":
                InitializeShiftInformationTab();
                break;
            default:
                MessageBox.Show(e.AddedItems[0].ToString());
                break;
        }
    }

    private void InitializeShiftInformationTab()
    {
        //here I want to add the new ShiftInformationItem
    }

}

更新2:

感謝所有評論,它顯示了,我的列表|| Panel為空。但是兩者都包含在主窗口中(在HoBusReceptionMain上方)

我在應用程序中使用功能區,並且選擇或加載功能區選項卡時,將觸發RibbonWin_SelectionChanged事件...功能區定義下方定義的列表或面板

我懷疑您在調用InitializeComponent()之前添加了它。

將添加的代碼移到InitializeComponent()下面 ,它將像從XAML一樣工作。 問題是控件沒有在調用InitializeComponent()之前InitializeComponent() ,因此導致NullReferenceException

public MainWindow()
{
    InitializeComponent();
    ShiftInformationList.Items.Add(new ShiftInformationItem());
    ShiftInformationPanel.Children.Add(new ShiftInformationItem());
    // ShiftInformationPanel is null here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM