我正在尝试循环选项卡控件的子元素,以了解哪些复选框设置为选中或未选中。我在SO上找到了各种答案,但我似乎无法让代码完成我需要的工作。以下是我到目前为止的情况:
foreach (System.Windows.Controls.TabItem page in this.MainWindowTabControl.Items)
{
if(VisualTreeHelper.GetChild(page, 0).GetType() == typeof(System.Windows.Controls.Grid))
{
var grid = VisualTreeHelper.GetChild(page, 0);
int gridChildCount = VisualTreeHelper.GetChildrenCount(grid);
for(int i = 0; i < gridChildCount; i++)
{
if(VisualTreeHelper.GetChild(grid, i).GetType() == typeof(CheckBox))
{
CheckBox box = (CheckBox)VisualTreeHelper.GetChild(grid, i);
if (boxer.IsChecked == true)
checkboxes.Add(box);
}
}
//do work
}
}
最有可能的是,我正在思考VisualTreeHelper类是如何工作的。我想我可以通过XAML代码继续工作以继续进入Tab Control的更深层次的孩子?目前,我在WPF的xaml上的代码如下所示:
<TabControl x:Name="MainWindowTabControl" HorizontalAlignment="Left" Height="470"
Margin="0,10,0,0" VerticalAlignment="Top" Width="1384">
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5" Margin="0,-21,0,0">
<CheckBox Name="testBox" Content="Check Box"
HorizontalAlignment="Left" VerticalAlignment="Top" Margin="1293,50,0,0"/>
</Grid>
</TabItem>
</TabControl>
所以,我的理解是我必须从子到孩子工作,这意味着,使用VisualTreeHelper获取Tab控件的子项(选择Tab项),然后获取TabItem的子项(选择网格),然后得到Grid的孩子,然后我终于可以循环遍历子项(复选框)以获取我想要的信息。如果我弄错了,有人可以解释我哪里出错吗?
编辑:将Checkbox XAML更改为正确的代码
答案 0 :(得分:1)
据我所知,没有必要做你正在做的事情让孩子从父母那里得到。您可以使用LogicalTreeHelper课程。它将允许您通过using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Script.Serialization;
using System.Web.Services;
namespace WebApplication2
{
[System.Web.Script.Services.ScriptService]
public partial class _Default : System.Web.Services.WebService
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string getJSON()
{
string jsonString = "";
// Read in file from a server side csv file.
String[] values = File.ReadAllText(@"EmployeeData.csv").Split(',', '\n');
int i = values.Length / 5;
Person[] Employees = new Person[i-1];
// Make list of employees and add their data from the csv file.
for (int k = 1; k < i; ++k)
{
string first = values[k * 5 + 1];
string last = values[k * 5];
string preferred = values[k * 5 + 2];
string position = values[k * 5 + 3];
string location = values[k * 5 + 4];
Person Person1 = new Person(first, last, preferred, position, location);
Employees[k-1] = Person1;
}
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
jsonString = javaScriptSerializer.Serialize(Employees);
return jsonString;
}
}
}
方法查询对象。
您的代码应如下所示:
XAML:
function searchName() {
$('#nameSearch').autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("Default.aspx/getJSON") %>',
data: JSON.stringify({}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
response(data);
},
error: function() {
alert('Something went wrong.');
}
});
},
});
}
C#:
GetChildren