C# WPF ホスト コンピューターの開発 (コントロールを動的に追加)

[免責事項:転載は歓迎ですが、商業目的での使用はご遠慮ください。連絡先メールアドレス: [email protected]]

        グラフィカル インターフェイス ソフトウェアを作成していると、よくある状況に遭遇します。つまり、グラフィカル インターフェイスに表示されるコントロールは可変である場合があります。表示されるコンテンツの具体的な量は、構成ファイルによって異なります。実はこれは私たちにとって少し恥ずかしいことなのです。結局のところ、ほとんどのシナリオでは、ソフトウェアを開いた後、どこでどのようなコンテンツが構成されているかがすでに決定されています。

        でもそんなことはなく、c# wpf ではこの点も考慮されており、コードを書くことで柔軟に追加や設定が可能です。結局のところ、xaml ファイルに残るのは空のグリッド インターフェイスだけです。

1.xaml インターフェイスの設計

        xaml インターフェイスは比較的シンプルですが、表示の便宜を考慮して 2 行に設計しました。最初の行の高さは 100 で、残りのスペースは 2 行目に予約されています。コントロールを配置するために、このグリッドには特別に mainGrid という名前が付けられました。

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="600">
    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="100" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid  Grid.Row="1" x:Name="mainGrid">
            <!-- Add your own layout here -->
        </Grid>
    </Grid>
</Window>

2.初期化ボタン

        このケースは、コントロールを追加する方法を示すだけです。追加されたコンテンツは比較的小さく、ボタンのみです。まずボタンを初期化し、ボタンのプロパティ (コンテンツ、幅、高さ) を設定します。同時に、このボタンに対してコールバック関数が設定されます。ボタンを設定したら、スタックパネルを作成し、このスタックパネルにボタンを設置します。最後の最も重要なステップは、スタック パネルを mainGrid のスペースに保存し、インターフェイス全体を実現することです。

        public MainWindow()
        {
            InitializeComponent();
            AddButtonDynamically();
        }

        private void AddButtonDynamically()
        {
            // 创建一个新的Button控件
            Button newButton = new Button();

            // 设置Button的属性
            newButton.Content = "Click me!";
            newButton.Width = 100;
            newButton.Height = 100;

            // 为Button添加Click事件处理程序
            newButton.Click += NewButton_Click;

            // 创建一个StackPanel并将Button添加到其中
            StackPanel stackPanel = new StackPanel();
            stackPanel.Children.Add(newButton);

            // 将StackPanel添加到窗口中的Grid中
            mainGrid.Children.Add(stackPanel);
        }

        ボタンのコールバック関数は次のとおりです。

        // Click事件处理程序
        private void NewButton_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Button Clicked!");
        }

3. マルチスレッドでインターフェースを更新する

        動的にスペースを追加するほかに注目すべき点は、インターフェイス部分の更新とマルチスレッド化です。スレッドの開始は非常に簡単ですが、新しいスレッドでインターフェイスを更新する場合は、これに注意する必要があります。この問題を説明するために、以下のインターフェースを更新します。

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="600">
    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="100" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Label x:Name="text" Grid.Row="0" Content="0" HorizontalAlignment="Center">
        </Label>
        <Grid  Grid.Row="1" x:Name="mainGrid">
            <!-- Add your own layout here -->
        </Grid>
    </Grid>
</Window>

        このインターフェイスと前のインターフェイスの違いは、行 0 に配置され、テキストという名前が付けられた追加のラベルがあることです。マルチスレッドを分析するには、まずマルチスレッド ライブラリを追加します。

using System.Threading;

        追加後、スレッドを作成し、スレッドを開始できます。一般に、各スレッドには対応するスレッド エントリ関数があります。

        public MainWindow()
        {
            InitializeComponent();
            AddButtonDynamically();

            Thread newThread = new Thread(new ThreadStart(ThreadMethod));
            newThread.Start();
        }

        private void ThreadMethod()
        {
            int cnt = 0;

            while(true)
            {
                cnt += 1;
                Dispatcher.Invoke(() =>
                {
                    // 在UI线程上执行操作(如果需要)
                    text.Content = Convert.ToString(cnt);
                });

                Thread.Sleep(1000);
            }
        }

        マルチスレッド動作は正常ですが、ここで注意が必要なのはテキストの更新部分です。つまり、インターフェイスのコンテンツを更新する必要がある場合は、Dispatcher.Invoke() メソッドを使用するのが最善です。

おすすめ

転載: blog.csdn.net/feixiaoxing/article/details/134997201