0

内容はファイルから取得する必要があるため、実行時にチェックボックスを作成するためにC#で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 */
}
4

1 に答える 1

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

}
于 2012-04-28T13:04:31.930 に答える