gpt4 book ai didi

c# - 过滤 CollectionViewSource

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:29 27 4
gpt4 key购买 nike

我想使用过滤器ComboBox 绑定(bind)到我的数据。为此,我创建了一个 TextBox 和一个 ComboBox。在后面的代码中,我读取了一个文件并生成了类 Channel 的对象,这些对象存储为 ComboBox 的项目。虽然编译器没有抛出错误,但过滤无法正常工作。如果我写了一些东西,数据就消失了,如果我删除,它又回来了。经过反复尝试,我意识到如果我开始输入“myNamespace.myChannel”(Unico.Canal),数据会保留,但不会过滤。确实是奇怪的行为。我怀疑我放错地方了。

enter image description here enter image description here enter image description here

(为了更好地理解我翻译了代码,Canal=Channel)

这是我的代码方案:

namespace Unico
{
public partial class ControlesArchivo : UserControl, INotifyPropertyChanged
{
public ControlesArchivo()
{

InitializeComponent();
}

public ObservableCollection<Channel> myListChannels //with INotifyPropertyChanged implemented. But I think I don't need it.

private void loadButton_Click(object sender, RoutedEventArgs e)
{

File loadedFile = new File();
loadedFile.read(); //Generates a bunch of data in lists.

foreach (Channel mychan in loadedFile.channels) //Just duplicating the data (maybe this can be avoided)
{
myListChannels.Add(mychan);
}

var view = CollectionViewSource.GetDefaultView(this.miListaDeCanales);
view.Filter = delegate(object o)
{
if (o.ToString().Contains(myTextBox.Text)) //Delicate place
{
return true;
}
return false;
};

myComboBox.ItemsSource = view;
DataContext = this;
}


private void myTextBox_TextChanged(object sender, TextChangedEventArgs e)
{


((ICollectionView)myComboBox.ItemsSource).Refresh();
myComboBox.SelectedIndex = 0;

}


}
}

数据在 XAML 中绑定(bind):

 ItemsSource="{Binding view}" 

编辑:我想我知道问题出在哪里:我没有指定要过滤的属性。我的意思是,您在 ComboBox 中看到的是 myListChannels 中列出的 class Channel 的属性 channelName。当我设置过滤器时,我不应该让我知道我在过滤什么吗?我怎么能写这个?非常感谢。

最佳答案

是的,你的假设是正确的。

我假设你的翻译,

public ObservableCollection<Channel> myListChannels;

实际上是

public ObservableCollection<Canal> miListaDeCanales;

在命名空间 Unico 中使用类 Canal

更新:

在您的过滤器中,尝试使用 ComboBox 中呈现的属性,而不是在 object 上使用 ToString()( o) 如果您没有从 System.Object 覆盖 ToString()

尝试切换

if (o.ToString().Contains(myTextBox.Text))

if (((Canal)o).NameProperty.Contains(myTextBox.Text))

^^ 这应该可以解决您的问题。

xaml 中是否有 ComboBox.ItemTemplateDataTemplate。这将解释为什么您在 ComboBox 中看到呈现的有效值,否则所有 ComboBoxItem 也将呈现为 Unico.Canal

关于c# - 过滤 CollectionViewSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16816983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com