2

私は C++ 開発者で、最近 C# に移行しました。4 つのラジオ ボタンを動的に生成する必要がある WPF アプリに取り組んでいます。私は多くの RnD を実行しようとしましたが、このシナリオはまれなようです。

XAML:

<RadioButton Content="Base 0x" Height="16" Name="radioButton1" Width="80" />

Contentシナリオは次のとおりです。次のように、このラジオ ボタンを 4 回生成する必要があります。

<RadioButton Content = Base 0x0 />
<RadioButton Content = Base 0x40 />
<RadioButton Content = Base 0x80 />
<RadioButton Content = Base 0xc0 />

次のように、C++ アプリケーションでこれを行いました。

#define MAX_FPGA_REGISTERS 0x40;

for(i = 0; i < 4; i++)
{
    m_registerBase[i] = new ToggleButton(String(T("Base 0x")) + String::toHexString(i * MAX_FPGA_REGISTERS));       
    addAndMakeVisible(m_registerBase[i]);
    m_registerBase[i]->addButtonListener(this);
}
m_registerBase[0]->setToggleState(true); 

上記に気づいた場合、 for ループが実行されるたびに コンテンツ名 がBase 0x0Base 0x40、 にbase 0x80なりbase 0xc0、最初のラジオボタンのトグル状態が true に設定されます。したがって、これら 4 つのボタンすべてにシングル ボタン クリック メソッドがあり、インデックスに基づいてそれぞれが操作を実行することに気付いた場合。

私のWPFアプリでこれを達成するにはどうすればよいですか? :)

4

1 に答える 1

7

私はあなたのために一連のコードを書くつもりでしたが、あなたの質問はおそらくここですでに回答されていることに気付きました: WPF/C# - プログラムでラジオボタンを作成して使用する例

もちろん、要件にもよりますが、おそらく最もクリーンな方法です。最も単純なケースが必要な場合は、次のとおりです。

Xaml:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid >
        <StackPanel x:Name="MyStackPanel" />

    </Grid>
</Window>

C#:

    public MainWindow()
    {
        InitializeComponent();

        for (int i = 0; i < 4; i++)
        {
            RadioButton rb = new RadioButton() { Content = "Radio button " + i, IsChecked = i == 0  };
            rb.Checked += (sender, args) => 
            {
                Console.WriteLine("Pressed " + ( sender as RadioButton ).Tag );
            };
            rb.Unchecked += (sender, args) => { /* Do stuff */ };
            rb.Tag = i;

            MyStackPanel.Children.Add( rb );
        }
    }

コンテンツやタグなどに必要なロジックを追加するだけです。

于 2012-10-23T06:41:24.687 に答える