2012-04-28 51 views
0

我在C#中編寫了一個WPF應用程序,在運行時創建複選框,因爲內容必須從文件中獲取。用戶從複選框中選擇項目。點擊按鈕時,所有選中的項目必須寫入文本文件。如何做呢? 以下代碼是否爲動態創建複選框的正確方法?如何獲取動態創建的複選框的選中項並將該值寫入WPF中的文件?

CheckBox chb; 
private void radioButton2_Checked(object sender, RoutedEventArgs e) 
{ 
    //Create file 
    string fp5 = @"D:\List.txt";  

    FileStream fs = new FileStream(fp5, FileMode.Open, FileAccess.Read); 
    StreamReader reader = new StreamReader(fs); 

    float cby = 135.0F; 
    int ControlIndex=1; 

    while (!reader.EndOfStream) 
    { 
     string line = reader.ReadLine(); 
     chb = new CheckBox(); 
     chb.Name = "Chk" + ControlIndex; 
     Canvas.SetLeft(chb, 28); 
     Canvas.SetTop(chb, cby); 
     chb.Content = line; 
     chb.IsChecked = false; 
     chb.Foreground = new SolidColorBrush(Colors.Blue); 
     myCanvas.Children.Add(chb); 
     cby = cby + 25.0F; 
     ControlIndex++; 
    } 
    fs.Close(); 
} 

private void button5_Click(object sender, RoutedEventArgs e) 
{ 
    //Create files 
    string fp6 = @"D:\List2.txt"; 

    if (!File.Exists(fp6)) 
    File.Create(fp6).Close(); 

    /*I want to write the checked items of the checkbox chb to the text file List2.txt. 
    I wanted to know how to do this */ 
} 

回答

2

你可以做到這一點

private void button5_Click(object sender, RoutedEventArgs e) 
{ 
string str=""; 
foreach (UIElement child in canvas.Children) 
{ 
    if(child is CheckBox) 
    if(((CheckBox)child).IsChecked) 
     str+=((CheckBox)child).Content; 

} 
string fp6 = @"D:\List2.txt"; 
File.WriteAllText(fp6,str); 

} 
+0

感謝!這很有幫助。 – Ashwini 2012-05-16 20:19:11

相關問題