你可以使用IEnumerable <type> </type>将数据绑定到ListBox

时间:2013-10-13 23:30:02

标签: c# data-binding mvvm windows-phone-8 listbox

我有以下xaml:

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="OrganisationTemplate">
        <Grid Margin="40,0,0,0">
            <StackPanel>
                <TextBlock Text="{Binding name}"></TextBlock>
            </StackPanel>
        </Grid>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

        <phone:PanoramaItem Header="Organisations">
            <ListBox Name="Organisation" ItemTemplate="{StaticResource OrganisationTemplate}" DataContext="{Binding Organisations, Mode=OneWay}" Margin="0,0,0,96"/>
        </phone:PanoramaItem>

我想知道绑定“组织”是否需要是List或ICollection或其他东西......或者它可以是IEnumerable。它只是它目前无法正常工作。

class DashboardViewModel
{
    private OrganisationRepository organisationRepository { get; set; }
    public IEnumerable<Organisation> Organisations { get; set; }

    public DashboardViewModel()
    {
        LoadOrganisationSection();
    }

    private async void LoadOrganisationSection()
    {
        organisationRepository = new OrganisationRepository();
        Organisations = await organisationRepository.GetAll();
        OnPropertyChanged("Organisations");
        //LoadBar loadBar = new LoadBar("Logging in");
        //loadBar.ShowLoadBar(this);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler tempEvent = PropertyChanged;

        if (tempEvent != null)
        {
            // property changed
            tempEvent(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

修改:: //

    public IEnumerable<Organisation> Organisations
    {
        get
        {
            return new Organisation[] { new Organisation { name = "hi" } };
        }
        set
        {
            OnPropertyChanged();
        }
    }

如果我这样做,我会收到一些东西,所以这是触发器无法正常工作。任何想法我该怎么做?当我等待organisationRepository.GetAll()完成..我需要onchange发生和更新。 DOH

1 个答案:

答案 0 :(得分:1)

尝试将listbox绑定到ItemsSource而不是设置其datacontext。 (假设您的viewmodel已设置为视图的datacontext)