2014-01-23 19 views
0

我创建一个Windows应用程序8.1,并有下面的代码:混合/ XAML:绑定的ItemsSource通过按钮

<ListView x:Name="listView" Height="505" Canvas.Left="35" Canvas.Top="75" Width="300" ItemTemplate="{StaticResource GroupTemplate}" ItemsSource="{Binding Groups, Mode=TwoWay, UpdateSourceTrigger=Explicit}" HorizontalAlignment="Left" VerticalAlignment="Top" UseLayoutRounding="False" ScrollViewer.VerticalScrollBarVisibility="Disabled" SelectionMode="None" /> 

<Button Height="40" Width="260" HorizontalAlignment="Left" VerticalAlignment="Top" Canvas.Left="40" Canvas.Top="585" BorderThickness="0" Content="Overige tonen" Background="#FF9B9B9B" Style="{StaticResource ButtonStyle1}" Click="show_items2" /> 

当用户点击该按钮show_items2ItemsSource组应该由另一ItemsSource所取代。我使用混合的sampleData“组”为Visual Studio 2013年我有按钮的非常明显的代码,如下图所示:

private void show_Medicatie2(object sender, RoutedEventArgs e) 
     { 
      // replace itemsSource with another 
     } 

我试过很多教程,但没有接缝的工作。我想念什么?帮助真的很感激。谢谢!

回答

0

您绑定到的类你需要RaisePropertyChanged("Groups")(在你的情况下,Groups所有者)需要为INotifyPropertyChanged,使您可以明确地告诉的WPF是绑定需要清爽。如果您未使用DependencyProperties,则这是一项要求。

添加到您的类定义:

class X : System.ComponentModel.INotifyPropertyChanged 
{ 
    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; 

    public IEnumerable<object> Groups //Replace 'object' with the type your are using... 
    { 
     get{ return m_Groups; } 
     set 
     { 
      m_Groups = value; 

      //Raise the event to notify that the property has actually got a new value 
      var handler = PropertyChanged; 
      if(handler != null) 
       PropertyChanged(this, new PropertyChangedEventArgs("Groups")); 
     } 
    } IEnumerable<object> m_Groups = new List<object>(); 
} 

为什么这项工作?

WPF知道约INotifyPropertyChanged并且当您使用对象作为绑定源时,WPF会检查它是否实现了该接口。如果有,WPF订阅该事件。触发事件时,将检查属性名称,如果它与绑定路径中的最后一个属性相匹配,则会更新绑定。

您也可以用ObservableCollection<T>代替IEnumerable<T>,但事情很快就会变得棘手。我建议读一下关于ObservableCollection<T>