Blend / XAML:通过按钮绑定ItemsSource

时间:2014-01-23 13:43:40

标签: c# xaml listview visual-studio-2013 blend

我正在创建一个Windows 8.1应用程序并具有以下代码:

<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_items2按钮时,ItemsSource组应由另一个ItemsSource替换。我在Blend for Visual Studio 2013中使用了samplingata'Groups'。我有非常明显的按钮代码,如下所示:

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

我尝试了很多教程但没有任何接缝可以工作。我错过了什么吗?非常感谢帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

更改RaisePropertyChanged("Groups")

时,您需要Groups

答案 1 :(得分:0)

您要绑定的类(在您的情况下,是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订阅该事件。触发事件时,将检查属性名称,如果它与绑定路径中的最后一个属性匹配,则更新绑定。

您也可以将IEnumerable<T>替换为ObservableCollection<T>但事后不久就开始变得棘手了。我建议阅读ObservableCollection<T>