【发布时间】:2012-05-18 08:12:51
【问题描述】:
我有一个名为 SeiveList 的 ObservableCollection。我想要列表中的所有 SeiveIdSize(除了最后一个,因为它没有用)并为 Combobox 设置 DataContext。我加了
seiveCmb.DataContext = GlobalUtils.SeiveList;
seiveCmb.DisplayMemberPath = // WHAT SHOULD GO HERE. hOW TO ONLY SHOW SeiveIdSize
// XML
<ComboBox Name="seiveCmb" ItemsSource="{Binding}" Grid.Column="1" Grid.Row="1" Margin="2" SelectedIndex="0" ></ComboBox>
根据 Sebastian 的建议进行了编辑: 目前,我刚刚尝试了组合框的列表。 我的Seive类:
public class Seive : INotifyPropertyChanged
{
// Other Members
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set
{
isSelected = value;
OnPropertyChanged("IsSelected");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string p)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(p));
}
}
在我的 Window .xaml 文件中:
<Window.Resources>
<CollectionViewSource Source="{Binding Path=comboSeives}"
x:Key="comboSeivesFiltered"
Filter="ComboSeiveFilter">
</CollectionViewSource>
</Window.Resources>
<ComboBox Name="seiveCmb" ItemsSource="{Binding Source={StaticResource comboSeivesFiltered}}" DisplayMemberPath="SeiveIdSize"
Grid.Column="1" Grid.Row="1" Margin="2" SelectedIndex="0"
></ComboBox>
在 Window .cs 文件中:
public ObservableCollection<Seive> comboSeives { get; set; }
// Initial original data in Window_Loaded method
comboSeives = GlobalUtils.SeiveList;
public void ComboSeiveFilter(object sender, FilterEventArgs e)
{
Seive sv = e.Item as Seive;
// Add items those is != "TOTAL" and isSelected == false
if (sv.SeiveIdSize != "TOTAL" && sv.IsSelected == false)
e.Accepted = true;
else
e.Accepted = false;
}
如果 id 为“TOTAL”或 isSelected 为 false(即未添加到网格中),则仅返回 true 并将其添加到其中。初始所有记录都有 isSelected = false。
这是我从this site的解释和帮助中了解到的。并实现了这一点。但是在运行时,我在组合框中看不到任何东西。我试图调试在过滤器方法添加中断,但它从未到达那里。你能指出我在上面的代码中犯错的地方吗?
感谢任何帮助。
谢谢
【问题讨论】:
-
你累了吗
seiveCmb.DisplayMemberPath = "SeiveIdSize";? -
你能展示
SeiveList的示例元素吗? -
@nemesv,是的,还添加了 DisplayMemberPath。如果是 xaml,请参见组合框。但还没有结果。
-
@StaWho,我不明白你所说的示例元素是什么意思。 SeiveList 的内容是:GlobalUtils.SeiveList.Add(new Seive("+10")); GlobalUtils.SeiveList.Add(new Seive("+8")); GlobalUtils.SeiveList.Add(new Seive());在窗口的构造函数中添加。当我调试时,我看到 comboSeives = GlobalUtils.SeiveList; comboSeives 里面也有 3 个项目。所以东西被添加进去了。在 ComboSeiveFilter 中,我只添加了 e.Accepted = true,但根本不会触发该方法——在该方法中添加了一个中断。
标签: wpf combobox field observablecollection datacontext