【问题标题】:UWP databindingUWP 数据绑定
【发布时间】:2018-04-13 02:06:42
【问题描述】:

我想在页面上使用表格进行布局。现在我有:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <ScrollViewer Grid.Row="0" Margin="10,0,10,0">
        <ListView 
            x:Name="NewsList" 
            HorizontalAlignment="Center">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Margin="15" Grid.Column="0" FontSize="25" Text="{Binding news_time}"/>
                        <TextBlock Margin="15" Grid.Column="1" FontSize="25" Text="{Binding title}"/>
                        <TextBlock Margin="15" Grid.Column="2" FontSize="25" Text="{Binding news_text}"/>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>

        </ListView>
    </ScrollViewer>
</Grid>

我想为我的ObservableCollection 对象绑定以将Grid 行动态添加到StackPanel 标记。这是我的.cs 文件。

public class News
{
    public int id;
    public string news_time;
    public string title;
    public string news_text;
}

public sealed partial class TermsAndNews : Page
{

    public ObservableCollection<News> newsCollection { get; set; } =
    new ObservableCollection<News>();
 // ...
    // Method called on initialization
    private async void GetData()
    {
        var httpClient = new HttpClient();

        var responsetNews = await httpClient.GetAsync("http://localhost:3000/news");

        responsetNews.EnsureSuccessStatusCode();

        string jsonNews = await responsetNews.Content.ReadAsStringAsync();

        this.newsCollection = JsonConvert.DeserializeObject<ObservableCollection<News>>(jsonNews);

        NewsList.ItemsSource = newsCollection;
    }
 }

运行代码后,没有任何显示。有什么想法吗?

【问题讨论】:

  • 你改变了实际的集合,并没有通知视图,而不是可观察集合的内容。

标签: c# xaml binding uwp


【解决方案1】:

尝试改变

this.newsCollection = ..... 

ObservableCollection<News> tempobcol = ...

然后遍历并添加到newsCollection

Foreach (News n in tempobcol)
{ newsCollection.Add(n); }

最后,删除

NewsList.ItemsSource = newsColleciton;

为了将其添加到 XAML

<ListView x:Name:"NewsList" ItemsSource:="{Binding newsCollection}"...../>

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多