我正在尝试制作新闻页面。我正在尝试在ListView中制作可扩展的List Items。
所以我写了一篇文章,我给它起了标题和文字。当文本长度超过5个字符时,应将文本切成前5个字符,然后您会看到类似“单击我展开”的内容。然后,单击该项目即可阅读全文。
现在我卡住了。我试图用DataTemplateSelector来解决它,但是DataTemplate
和string
互相影响,我不知道该怎么解决。
xaml:
<ListView x:Name="NewsList" HasUnevenRows="true">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame BorderColor="Black">
<StackLayout>
<StackLayout>
<Image HeightRequest="50" WidthRequest="50" Source="https://xamarin.com/content/images/pages/forms/example-app.png" />
</StackLayout>
<Label Text="{Binding Title}" />
<Label Text="{Binding Text}" />
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
cs:
public class NewsEntry
{
public string Title { get; set; }
// public string Text { get; set; }
public TestDTS tex { get; set; }
}
public class TestDTS : DataTemplateSelector
{
// public DataTemplate titel { get; set; }
public DataTemplate texd { get; set; }
public DataTemplate texdCut
{
get { return texd.ToString().Substring(0,5);} // cannot implicitly convert string to DataTemplate
}
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
return item.ToString().Length > 7 ? texdCut : texd;
}
}
编辑
我找到了另一种解决方法:
MessagingCenter.Subscribe<WriteArticle, NewsEntry>(this, "Spiderman", (p, item) =>
{
var finishedNews = item as NewsEntry;
if (finishedNews.TextFull.Length > 18)
{
finishedNews.Text = finishedNews.TextCut;
}
else finishedNews.Text = finishedNews.TextFull;
newsEntries.Insert(0, finishedNews);
});
//....
public void NewsList_Selected(Object sender, SelectedItemChangedEventArgs e)
{
newsEntries[0].Text = newsEntries[0].TextFull;
NewsList.ItemsSource = null;
NewsList.ItemsSource = newsEntries;
}
//....
public class NewsEntry
{
public string Title { get; set; }
public string Text { get; set; }
public string TextFull { get; set; }
public string TextCut
{
get { return TextFull.Substring(0, 10) + " but wait. theres more"; }
}
}
但是现在我想知道是否有人知道如何更新ListView?我通过将ItemSource设置为null并返回newsEntries来完成此操作。我似乎找不到其他方法。