【发布时间】:2016-05-20 09:22:41
【问题描述】:
我有两种类型的站点列表,我通过下面的代码在视图模型中过滤
public void FilterSite()
{
if (SelectedItem.Contains("EC350"))
listofsites = new ObservableCollection<SiteDetails>(listofsites.Where(p => Convert.ToString(p.DeviceType) == "MiCell_Ec350"));
else if (SelectedItem.Contains("MiCell"))
listofsites = new ObservableCollection<SiteDetails>(listofsites.Where(p => Convert.ToString(p.DeviceType) == "MiCell"));
else if (SelectedItem.Contains("Mini-Max"))
listofsites = new ObservableCollection<SiteDetails>(listofsites.Where(p => Convert.ToString(p.DeviceType) == "Mini-Max"));
}
现在为了在 listofsites 中获取自动更新,我正在属性设置器中实现 InotifyPropertyChanged 和 OnPropertyChanged p>
public class SiteMainUC_VM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private ObservableCollection<SiteDetails> listofsites = null;
public ObservableCollection<SiteDetails> Listofsites
{
get
{
return listofsites;
}
set
{
listofsites = value;
OnPropertyChanged("Listofsites");
}
}
在组合框选择值后,通过调试我看到过滤值但视图未显示。现在对于绑定,我已经尝试了单向/双向,但没有工作。下面是xaml代码-
<ComboBox Name="cmbSiteSearch" SelectedValue="{Binding SelectedItem, Mode=TwoWay}" Text="{Binding SearchFilter,UpdateSourceTrigger=PropertyChanged}" Height="18" Width="18" IsReadOnly="True" FontFamily="Arial" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ComboBox.Background>
<ImageBrush ImageSource="/MasterLink;component/Resources/i_filter.png" />
</ComboBox.Background>
<ComboBoxItem Content="All" Height="34" Width="190" FontFamily="Arial" FontSize="12" />
<ComboBoxItem Content="EC350" Height="34" Width="190" FontFamily="Arial" FontSize="12"/>
<ComboBoxItem Content="Mini-Max" Height="34" Width="190" FontFamily="Arial" FontSize="12"/>
</ComboBox>
现在我有站点列表列表框代码
<ListBox ItemsSource="{Binding Listofsites}" SelectedItem="{Binding Path=Selectedsites, Mode=TwoWay,NotifyOnSourceUpdated=True}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="600"
SelectionChanged="ListBox_SelectionChanged" >
【问题讨论】:
-
使用 Observable 集合,您不必实现 OnPropertyChanged,而是应该使用 Collection.Clear()。并将所有新项目添加到集合中,例如 Collection.Add(filteredItem)
-
试过了。但没有得到。
-
您是否也对子视图模型(即 SiteDetails)做了同样的通知
-
不,没有,因为客户端提供的所有数据都来自此应用程序的 api [dll]。既然你说我就试试。感谢您的提示。
标签: c# wpf c#-4.0 mvvm combobox