我在 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 */
}