有没有人试过过滤控件列表?我有一些简单的示例代码可以说明一个我似乎无法解决的问题。过滤文本列表时我没有问题,但是当我将列表转换为可观察的控件列表时,我运行的任何过滤器都会影响其他过滤器。这是一些有效的示例代码
代码:
public partial class MainWindow : Window
{
public ObservableCollection<string> testOC { get; set; }
public MainWindow()
{
InitializeComponent();
testOC = new ObservableCollection<string>();
for (int i = 0; i < 20; i++)
{
testOC.Add("Test Stuff " + i);
}
ListCollectionView view1 = new ListCollectionView(testOC);
ListCollectionView view2 = new ListCollectionView(testOC);
view1.Filter = Filter1;
view2.Filter = Filter2;
leftGrid.ItemsSource = testOC;
MiddleGrid.ItemsSource = view1;
rightGrid.ItemsSource = view2;
}
private bool Filter1(object test)
{
try
{
var testStuff = test as string;
if (testStuff.Contains("1"))
{
return true;
}
return false;
}
catch (Exception)
{
throw;
}
}
private bool Filter2(object test)
{
try
{
var testStuff = test as string;
if (testStuff.Contains("2"))
{
return true;
}
return false;
}
catch (Exception)
{
throw;
}
}
}
XML:
<Window x:Class="testTheFilter.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:testTheFilter"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="775"/>
</Grid.RowDefinitions>
<ItemsControl Name="leftGrid" Grid.Column="0" Grid.RowSpan="2"/>
<ItemsControl Name="MiddleGrid" Grid.Column="1" Grid.RowSpan="2"/>
<ItemsControl Name="rightGrid" Grid.Column="2" Grid.RowSpan="2"/>
</Grid>
这可以正常工作,您会得到三个列表,第一个列表包含所有字符串,第二个列表仅包含带有 1 的字符串,第三个列表仅包含带有 2 的字符串。
现在,如果我采用完全相同的代码并将其更改为控件列表,它就会变得不稳定
这是代码部分:
public partial class MainWindow : Window
{
public ObservableCollection<Button> testOC { get; set; }
public MainWindow()
{
InitializeComponent();
testOC = new ObservableCollection<Button>();
for (int i = 0; i < 20; i++)
{
Button btn = new Button();
btn.Content = "Test Stuff " + i;
testOC.Add(btn);
}
ListCollectionView view1 = new ListCollectionView(testOC);
ListCollectionView view2 = new ListCollectionView(testOC);
view1.Filter = Filter1;
view2.Filter = Filter2;
leftGrid.ItemsSource = testOC;
MiddleGrid.ItemsSource = view1;
rightGrid.ItemsSource = view2;
}
private bool Filter1(object test)
{
try
{
var testStuff = test as Button;
if (testStuff.Content.ToString().Contains("1"))
{
return true;
}
return false;
}
catch (Exception)
{
throw;
}
}
private bool Filter2(object test)
{
try
{
var testStuff = test as Button;
if (testStuff.Content.ToString().Contains("2"))
{
return true;
}
return false;
}
catch (Exception)
{
throw;
}
}
}
有没有人见过这种行为,有谁知道如何解决这个问题?我花了几个小时研究这个,似乎找不到解决办法。
提前致谢