我有一个包含复选框的列表框。我想在字符串数组中获取所有复选框选中的项目内容。我怎么能得到这个?
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="TrackingView1" Margin="9,0,2,5">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="fileNameLinkButton" Content="{Binding BindsDirectlyToSource=True}" FontFamily="Segoe WP Semibold" Foreground="Black" FontSize="20" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
答案 0 :(得分:3)
您可以使用VisualTreeHelper检索datatemplate项目, 使用此方法获取datatemplate的第一项
//method for finding first element of the listbox data template
private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
{ return (T)child; }
else
{
var result = FindFirstElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
然后在您想要的事件中使用此代码,例如在按钮上单击
int itemsCount = this.TrackingView1.Items.Count;
List<string> myList = new List<string>();
for (int i = 0; i < itemsCount; i++)
{
ListBoxItem item = (ListBoxItem)this.TrackingView1.ItemContainerGenerator.ContainerFromIndex(i);
CheckBox tagregCheckBox = FindFirstElementInVisualTree<CheckBox>(item);
if((bool)tagregCheckBox.IsChecked)
myList.Add(tagregCheckBox.Content.ToString());
}
答案 1 :(得分:0)
在经典的TextBook方法中,您可以将“TrackingView1”绑定到IList,其中PersonClass看起来像
public class PersonClass
{
public string Name { get; set; }
public bool IsSelected { get; set; }
public PersonClass(string name, bool isSelected)
{
this.Name = name;
this.IsSelected = isSelected;
}
}
并且您想要收集数据
string[] checkedNames = (from name in Names
where name.IsSelected
select name.Name).ToArray();
我实际上会避免ToArray(),并直接访问UI