如何通过 C# 代码设置 LongListSelector.ItemSource,如 ItemsSource= "{Binding CustomSounds.Items}"


            <phone:LongListSelector 
                Margin="0,0,-12,0" 
                ItemsSource="{Binding CustomSounds.Items}"
                LayoutMode="Grid"
                GridCellSize="150,150"
                ItemTemplate="{StaticResource CustomSoundTileDataTemplate}" 
                SelectionChanged="LongListSelector_SelectionChanged" 
                x:Name="CustomSoundLongListSelector"
                />

我有一个这样的LongListSelector,现在我在CustomSounds.Items中更改了一些东西,并想重新加载它。如何在代码隐藏文件中执行此操作,CustomSoundLongListSelector.ItemSource = ...

你应该在代码隐藏中这样做:

CustomSoundLongListSelector.ItemsSource = model.CustomSounds.Items;

请注意,"模型"是在您的页面上设置的DataContext,或者更具体地说是在LongListSelector上设置的。

您可能希望在 ViewModel 中实现 INotifyPropertyChanged 接口,以通知视图重新加载数据。我认为这是 MVVM 中非常标准的模式。

本质上:

公共类视图模型:INotifyPropertyChanged {

//... your other VM stuff...
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (null != handler)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
} }

然后,当您更改项目时,您会说:

通知属性已更改("项目");

如果要将可观察集合用于项源 您不必实现INotifyPropertyChanged 它将自行工作

最新更新