簡體   English   中英

將Gridview項目源綁定到ViewModel屬性

[英]Issue binding Gridview itemsource to viewmodel property

我在將視圖模型中的collection屬性綁定到GridView時遇到一些問題。 我正在使用MVVM light,我相信我已經正確設置了ViewModelLocator,並且在頁面的xaml中設置了DataContext。

模型

public class Base
{
    public ObservableCollection<Downloads> results { get; set; }
}
public class Downloads
{
    public int id { get; set; }
    public string name { get; set; }
    public int trackNumber { get; set; }
    public string mixName { get; set; }
    public string title { get; set; }
    public string slug { get; set; }
    public string releaseDate { get; set; }
    public string publishDate { get; set; }
    public List<Artist> artists { get; set; }
    public string artistNames
    {
        get
        {
            return (artists == null)
                ? string.Empty
                : string.Join(", ", artists.Select(a => a.name));
        }
    }
    public string artistNamesSlug
    {
        get
        {
            return (artists == null)
                ? string.Empty
                : string.Join("_", artists.Select(a => a.name));
        }
    }

    public Release release { get; set; }
    public Label label { get; set; }
    public Image images { get; set; }
    public int downloadId { get; set; }
    public string audioFormat { get; set; }
    public string downloadUrl { get; set; }
}
public class Release
{
    public int id { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string slug { get; set; }
}
public class Label
{
    public int id { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string slug { get; set; }
    public bool status { get; set; }
}
public class Image
{
    public LargeImage large { get; set; }
}
public class LargeImage
{
    public int id { get; set; }
    public int width { get; set; }
    public int height { get; set; }
    public string url { get; set; }
    public string secureUrl { get; set; }
}

視圖模型

public class AvailableViewModel : ViewModelBase
{

    public AvailableViewModel()
    {

    }

    private Base availableDownloads;
    public Base AvailableDownloads
    {
        get
        {
            if(availableDownloads == null)
            {
                GetData();
            }
            return availableDownloads;
        }
        set
        {
            availableDownloads = value;
            RaisePropertyChanged(() => AvailableDownloads);
        }
    }

    private async void GetData()
    {
        OAuth oauth = new OAuth();

        string httpMethod = "GET";
        string parameters = "status=available";
        string response = await oauth.GetData(OAuth.availDownloadsUrl, httpMethod, parameters);

        Base availableDownloads = JsonConvert.DeserializeObject<Base>(response);
    }
}

XAML

DataContext="{Binding Available, Source={StaticResource Locator}}">

<Page.Resources>
    <DataTemplate x:Key="AvailableGridView">
        <Grid Margin="0,10,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="2*"/>
            </Grid.ColumnDefinitions>
            <Image Source="{Binding AvailableDownloads.images.large.url}" Grid.Column="0" />
            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="20,0,0,0">
                <TextBlock Text="{Binding AvailableDownloads.title}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="Wrap"/>
                <TextBlock Text="{Binding AvailableDownloads.release.name}" Style="{StaticResource BaseTextBlockStyle}"/>
                <TextBlock Text="{Binding AvailableDownloads.artistNames}" Style="{StaticResource SubtitleTextBlockStyle}"/>
            </StackPanel>
        </Grid>
    </DataTemplate>
</Page.Resources>


<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <GridView ItemsSource="{Binding AvailableDownloads.results}" SelectionMode="Multiple" ItemTemplate="{StaticResource AvailableGridView}"/>
</Grid>

這可能是問題的一部分,但是當我在xaml中設置DataContext時,布局會顯示“對象引用”錯誤。 我不知道為什么會這樣,但是應用程序會編譯並運行。 我是MVVM的新手,我似乎無法弄清楚為什么我的綁定在這里不起作用。

這可能是問題的一部分,但是當我在xaml中設置DataContext時,布局會顯示“對象引用”錯誤。

這是“對象引用錯誤” NullReferenceException錯誤嗎? 由於您的代碼不全面,因此我可以在多個地方重現此問題,但我不知道是什么導致了您的問題。

首先,我在這里更改了XAML代碼以進行測試,並在GridViewDataTemplate中使用了x:Bind:

  ...
  DataContext="{Binding Available, Source={StaticResource Locator}}"
  xmlns:model="using:[Namespace of your app].Model">
<Page.Resources>
    <DataTemplate x:Key="AvailableGridView" x:DataType="model:Downloads">
        <Grid Margin="0,10,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="2*" />
            </Grid.ColumnDefinitions>
            <!--<Image Source="{x:Bind downloadUrl}" Grid.Column="0" />-->
            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="20,0,0,0">
                <TextBlock Text="{x:Bind title}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="Wrap" />
                <TextBlock Text="{x:Bind release.name}" Style="{StaticResource BaseTextBlockStyle}" />
                <TextBlock Text="{x:Bind artistNames}" Style="{StaticResource SubtitleTextBlockStyle}" />
            </StackPanel>
        </Grid>
    </DataTemplate>
</Page.Resources>

<Grid>
    <GridView ItemsSource="{Binding AvailableDownloads.results}" SelectionMode="Multiple" ItemTemplate="{StaticResource AvailableGridView}" />
</Grid>

我像這樣更改了您的Base類:

public class Base
{
    public ObservableCollection<Downloads> results { get; set; }

    public Base()
    {
        results = new ObservableCollection<Downloads>();
    }
}

如果您在添加數據時未創建ObservableCollection<Downloads>的新實例,則可能是一個可能的原因。

我這樣更改了AvailableViewModel() ,添加到result中的數據是偽造的,僅用於測試:

public AvailableViewModel()
{
    availableDownloads = new Base();
    availableDownloads.results.Add(new Downloads { title = "11111", artistNames = "222", release = new Release(0, "333", "", "") });
    availableDownloads.results.Add(new Downloads { title = "11111" });
    availableDownloads.results.Add(new Downloads { title = "11111" });
    availableDownloads.results.Add(new Downloads { title = "11111" });
    availableDownloads.results.Add(new Downloads { title = "11111" });
}

如您所見,我在這里創建了一個新的Base類實例。

我注意到在您的xaml代碼中,您使用了release.name ,為此,我認為您需要像下面這樣修改Release類:

public class Release
{
    public Release()
    {
    }

    public Release(int Id, string Name, string Type, string Slug)
    {
        this.id = Id;
        this.name = Name;
        this.type = Type;
        this.slug = Slug;
    }

    public int id { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string slug { get; set; }
}

您可以這樣創建Release類的實例:

release = new Release(0, "333", "", "");

我在DataTemplate評論了Image控件,要完成此工作,您需要像Release類一樣修改LargeImageImage

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM