簡體   English   中英

WPF 將元素添加到 UI

[英]WPF add element to UI

超級基本的問題,我只想在我的 window 中添加一個 label。 我查看了類似的問題,但沒有找到答案。

我有我的 XAML 代碼:

<Window [some preset values...]
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="childGrid"></Grid>
</Window>

還有我的 C# 代碼:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            Label testLabel = new Label();
            testLabel.Content = "TEST";
            this.AddChild(testLabel);
        }
    }

window 上沒有顯示任何內容,也沒有引發錯誤。 我需要什么 c# 代碼來解決這個問題?

您應該將InitializeComponent()默認調用保留在構造函數中以便開始。

那么,一個Window只能有一個孩子,所以你應該設置它的Content來替換你已經有的Grid

public MainWindow() {
    InitializeComponent();
    Label testLabel = new Label();
    testLabel.Content = "TEST";
    this.Content = testLabel;
}

最后,這不是在 WPF 中設計的工作方式,這與 Windows Forms 中的原理不同。 如果你想從一開始就在MainWindow中定義你的Label ,你應該在 XAML 中定義它,如下所示:

<Window>
    <Label Content="Test"></Label>
</Window>

如果你想要一個Grid和一個Label里面,就這樣吧,但你可能應該閱讀更多關於 XAML 和 WPF 的介紹,如果你不想從頭開始:

<Window>
    <StackPanel>
        <Grid Name="childGrid">
            <Label Content="Test"></Label>
        </Grid>
    </StackPanel>
</Window>

您可以利用 wpf 的 XAML,而不是使用代碼隱藏:

<Window [some preset values...]
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="childGrid">
        <Label Content="Test"></Label>
    </Grid>
</Window>

(未測試,匆忙寫了)

看看這個很好的指南,我曾經學習如何使用 WPF 來制作一個簡單的桌面應用程序: https://www.wpf-tutorial.com/basic-controls/the-label-control/

暫無
暫無

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

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