2012-10-23 98 views
1

我是C++開發人員,最近轉向了C#。我正在開發一個WPF應用程序,我需要動態生成4個單選按鈕。我試圖做很多RnD,但看起來像這種情況很少見。動態生成WPF中具有不同內容的RadioButton集合

XAML:

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

現在這裏是情景:我應該產生此單選按鈕4次不同Content如下:

<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); 

如果您注意以上情況,每次循環運行的內容名稱將變爲Base 0x0,Base 0x40,base 0x80base 0xc0,並將第一個單選按鈕的切換狀態設置爲true。因此,如果您注意到所有這4個按鈕都會有單按鈕單擊方法,並且會根據索引執行操作。

我如何在我的WPF應用程序中實現此目的? :)

回答

5

我打算寫一組代碼對你,但意識到你的問題可能已經在這裏找到答案: WPF/C# - example for programmatically create & use Radio Buttons

它可能做的,這取決於你的課程要求的最徹底的方法。如果你想最簡單的情況,那就是:

的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); 
     } 
    } 

只需添加你需要的任何邏輯的內容,標籤等。

+0

非常感謝好友:) MVVM是我想採取的方法。但我可以看到他有2個按鈕點擊事件。這是我的MVVM方法中需要的嗎? – StonedJesus

+0

不,這不是必需的。我還想指出,事件處理程序是以「非MVVM」的方式添加的,因爲它們是在窗口的代碼隱藏中設置的,而不是通過XAML和視圖模型設置的。你會做的是使用樣式在單選按鈕的IsChecked屬性上設置綁定。 在任何情況下,您都可以訂閱或忽略您想要的任何事件。 – FanerYedermann

+0

這看起來不錯。我試圖實現MVVM方法,看起來很安靜。 Y我們的方法也簡單得多:) – StonedJesus