我想根據搜索框篩選所選列的數據。我有這個迄今爲止,在此基礎上一篇:filter wpf datagrid values from a textbox如何過濾DataGrid中的記錄?
DataGridCollection:
public ICollectionView DataGridCollection
{
get { return _dataGridCollection; }
set { _dataGridCollection = value; NotifyPropertyChanged("DataGridCollection"); }
}
過濾收集:
private void FilterCollection()
{
if (_dataGridCollection != null)
{
_dataGridCollection.Refresh();
}
}
數據來源:
DataTable pixsellOrders = SqlConnect(query);
Grid.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate { DataGridCollection = CollectionViewSource.GetDefaultView(pixsellOrders); });
DataGridCollection.Filter = new Predicate<object>(filter);
過濾器按鈕(右點擊):
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
string filter = "";
FilterBox.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate { filter = FilterBox.Text; });
if (filter == "")
{
Console.WriteLine("no filter");
return;
}
else
{
Console.WriteLine(filter);
FilterCollection();
}
}
基於例如:
private bool filter(object item)
{
if (item.Subject.Contains(_searchstr) || item.Reference.Contains(searchstr))
{
return true;
}
return false;
}
XAML:
<Grid DataContext="{Binding ElementName=ResultsWindow}">
<DataGrid x:Name="Grid" HorizontalAlignment="Stretch" Height="Auto" Margin="20,45,20,60" VerticalAlignment="Stretch" Width="Auto" ItemsSource="{Binding DataGridCollection}" >
<DataGrid.Resources>
<ContextMenu x:Key="DataGridColumnHeaderContextMenu">
<MenuItem Header="Filter" Click="MenuItem_Click"/>
</ContextMenu>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContextMenu"
Value="{StaticResource DataGridColumnHeaderContextMenu}"/>
</Style>
</DataGrid.Resources>
</DataGrid>
<Button x:Name="BtnBack" Content="Back" HorizontalAlignment="Right" Margin="0,0,20,20" VerticalAlignment="Bottom" Width="76" Click="BtnBack_Click"/>
<TextBox Height="27" Margin="65,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Left" Width="524" Name="FilterBox"/>
<Label Content="Filter" HorizontalAlignment="Left" Margin="20,10,0,0" VerticalAlignment="Top"/>
</Grid>
在列明確地在過濾器(私人布爾濾波器)所聲明的例子。我只想在所選的列上進行過濾(右鍵單擊列標題並從上下文菜單中選擇過濾器)。我如何調整我必須做的事情?不幸的是,我對XAML沒有多少經驗。
用戶從未擦着立柱,列從SQL查詢填充。我希望用戶在搜索框中輸入一個字符串,然後過濾該字符串上的一列(在該列的所有行中搜索該字符串)。這可能是我誤解你的答案 – Jackimedes
基本上我所建議的是一個像StackOverflow(https://stackoverflow.com/help/searching)上的搜索框,它很簡單易用。 – Aybe