0

我有一个包含复选框的列表框。我想在字符串数组中获取所有复选框选中的项目内容。我怎样才能得到这个?

<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>
4

2 回答 2

3

您可以使用 VisualTreeHelper 检索数据模板项,使用此方法获取数据模板的第一项

 //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());
 }
于 2012-07-04T06:20:01.170 回答
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

于 2012-07-02T07:38:26.987 回答