我从MySQL数据库填充TreeView
。所以我不为每个人上课。我使用HierarchicalDataTemplate
来构造TreeView,我有三个级别。我想过滤比较包含的TextBlock
文本和用户输入的第一级。如何在不使用ObservableCollection
的情况下进行过滤? (我尝试使用ICollectionView
,但我失败了。)
Source = CollectionViewSource.GetDefaultView(FileTreeView.ItemsSource);
this.Source.Filter = item =>
{
TreeViewItem vitem = item as TreeViewItem;
if (vitem == null) return false;
foreach (object items in vitem.Items)
{
vitem.ApplyTemplate();
TreeViewItem firstlevel = vitem.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
UIElement element = GetChildControl(firstlevel, "fem_title");
if (element != null)
{
TextBlock txt = (TextBlock)element;
return (txt.Text.Contains(title.SelectedValue.ToString()));
}
}
return false;
它会抛出" NotSupportedException"。
我如何填充TreeView:
private DataSet FillDataGrid()
{
try
{
MySqlConnection con = new MySqlConnection();
con.ConnectionString = ConString;
con.Open();
MySqlDataAdapter femda = new MySqlDataAdapter("SELECT * FROM fem_table", con);
MySqlDataAdapter versionda = new MySqlDataAdapter("SELECT * FROM version_table", con);
MySqlDataAdapter fileda = new MySqlDataAdapter("SELECT * FROM file_table", con);
DataSet ds = new DataSet();
femda.Fill(ds, "fem_table");
versionda.Fill(ds, "version_table");
fileda.Fill(ds, "file_table");
DataRelation dr = new DataRelation("DataRelationship_fem_version",
ds.Tables["fem_table"].Columns["fem_guid"],
ds.Tables["version_table"].Columns["fem_table_fem_guid"],
true);
DataRelation dr2 = new DataRelation("DataRelationship_version_file",
ds.Tables["version_table"].Columns["version_id"],
ds.Tables["file_table"].Columns["version_table_version_id"],
true);
dr.Nested = true;
ds.Relations.Add(dr);
ds.Relations.Add(dr2);
return ds;
}
catch (Exception ex)
{ throw new Exception(ex.Message); }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.FileTreeView.DataContext = FillDataGrid();
}
答案 0 :(得分:1)
过滤器使用基础数据,而不是UIElements。由于您不使用类来表示TreeViewItem并仅使用字符串填充它们,因此您的项目实际上是一个字符串。 这有效:
public partial class MainWindow : Window
{
public List<string> Test = new List<string>() { "test", "someothertext" };
public MainWindow()
{
InitializeComponent();
treeView.ItemsSource = Test;
var Source = CollectionViewSource.GetDefaultView(treeView.ItemsSource);
string search_text = "test";
Source.Filter = item =>
{
return item.ToString().Contains(search_text);
};
}
}
我不明白你是否使用多个文本框进行过滤,但是如果你不这样做,你应该给一个名字并使用它的文字,如
string search_text = txtbox.Text;