我有一個名爲SeiveList的ObservableCollection。我想從列表中選擇所有的SeiveIdSize(除了最後一個沒有用),並且爲Combobox設置DataContext。我加WPF:從ObservableCollection獲取特定字段
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的建議:目前,我只是嘗試了與列表下拉框。 我的鈦硅分子篩類:
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));
}
}
在我窗口的.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>
窗口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是 「總」 或isSelected是假的(即沒有添加到網格中),那麼只返回true,它會加起來。初始的所有記錄都有isSelected = false。
這是我從你的解釋和this site的幫助中瞭解到的。並已實施這一點。但在運行時,我沒有看到組合框中的任何東西。我試圖在過濾器方法中調試添加break,但它永遠不會到達那裏。你能指出我從上面的代碼中弄錯了什麼嗎?
aNY幫助被讚賞。
謝謝
你累了嗎'seiveCmb.DisplayMemberPath =「SeiveIdSize」;'? – nemesv
你可以顯示一個「SeiveList」的例子元素嗎? – StaWho
@nemesv,是的,也添加了DisplayMemberPath。查看組合框,如果xaml。但沒有結果。 – Tvd