我从.txt文件中提取后列出了结果列表。我想在列出的每个结果后面添加一个复选框。以下是我的代码:
private void LoadFile() {
List<string> lines = new List<string>();
try
{
StreamReader sr = new StreamReader("test.txt");
while (!sr.EndOfStream)
{
lines.Add(sr.ReadLine());
}
sr.Close();
for (int i = 3; i < lines.Count; i++)
{
resultsTreeView.Items.Add(lines[i].ToString().Substring(67,17));
resultsTreeView.Items.Add(CheckBox[i]);
}
如何添加复选框,因为提取的结果每次都会更改?我想跟踪哪些框已经检查过,以便我可以将结果打印给用户。谢谢!
答案 0 :(得分:0)
for (int i = 3; i < lines.Count; i++)
{
resultsTreeView.Items.Add(lines[i].ToString().Substring(67,17));
resultsTreeView.Items.Add(new CheckBox());
// resultsTreeView.Items.Add(BuildCheckBox())
}
OR
CheckBox BuildCheckbox()
{
CheckBox C = new CheckBox();
return C;
}
这就是创建复选框所需的全部内容,或者您可以创建一个返回复选框的函数,在其中创建复选框的新实例,并按照您想要的方式设置属性/订阅事件并将其返回。
对于选中复选框的跟踪,我只需要您提供“resultsTreeView”的类型
编辑:
循环遍历TreeView中的复选框并对选中的复选框执行操作:
resultsTreeView.Items.OfType<CheckBox>().ToList()
.ForEach(C =>
{
if (C.IsChecked.HasValue && C.IsChecked.Value == true)
{
//DoSomething
}
});
答案 1 :(得分:0)
我不确定你到底在找什么。我假设resultsTreeView是一个TreeViewItem。而且我还假设你在wpf工作。您可以通过wpf执行以下操作。
for (int i = 0; i < lines.Count(); i++)
{
resultsTreeView.Items.Add(lines[i].ToString().Substring(67,17));
}
<TreeView x:Name="resultsTreeView" HorizontalAlignment="Left" Height="100" Margin="37,344,0,0" VerticalAlignment="Top" Width="257" >
<TreeView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}"/>
<CheckBox/>
</StackPanel>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
可以通过
背后的代码完成类似的事情for (int i = 0; i < mylist.Count(); i++)
{
resultsTreeView.Items.Add(mylist[i]);
}
resultsTreeView.ItemTemplate = TreeViewDataTemp;
然后按以下方式创建TreeViewDataTemp
private static DataTemplate TreeViewDataTemp
{
get
{
DataTemplate TVDT = new DataTemplate();
FrameworkElementFactory Stack = new FrameworkElementFactory(typeof(StackPanel));
Stack.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
FrameworkElementFactory TextB = new FrameworkElementFactory(typeof(TextBlock));
TextB.SetValue(TextBlock.TextProperty, new Binding());
FrameworkElementFactory ChkBox = new FrameworkElementFactory(typeof(CheckBox));
Stack.AppendChild(TextB);
Stack.AppendChild(ChkBox);
TVDT.VisualTree = Stack;
return TVDT;
}
}
上面给出了1个项目,它是一个文本和一个复选框。 或者,您的方法将在您添加的每个字符串项后添加一个复选框作为新项目。这是
for (int I=0; I<lines.Count(); I++)
{
resultsTreeView.Items.Add(mylist[i]);
resultsTreeView.Items.Add(new CheckBox());
}