在我正在制作的应用程序中,我使用下面的XML显示帖子。事情是我需要它才能够轻松重用,现在每个显示帖子的类都需要XML,所以每当我改变一个值时,我必须通过所有类来为每个页面更改它。
所以我的主要问题是,是否可以将FormatPosts方法移动到名为LayoutUtils的C#类,因此在每个页面的构造函数上我只使用LayoutUtils.FormatPosts
并返回解析的所有东西,并将XML合并为一个class so如果我更改它,它会在任何地方更新它?
我使用的XML代码是;
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage *snip*>
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="TextPostTemplate">
<ViewCell>
<StackLayout BackgroundColor="White" Margin="10, 10, 10, 10" Padding="10, 10, 10, 10">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" TextColor = "Black" FontSize = "15"/>
</StackLayout>
<Label Text="{Binding Body}" TextColor = "Black"/>
<StackLayout Orientation="Horizontal" Padding="0, 0, 0, 5">
<Label Text="{Binding Likes}" FontSize="15" TextColor="Black" Margin="10, 0, 0, 0"/>
<Image Source="{Binding LikeSource}" HeightRequest = "22" HorizontalOptions = "StartAndExpand"/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
<DataTemplate x:Key="InvalidPostTemplate">
<ViewCell>
<StackLayout BackgroundColor="White" Margin="10, 10, 10, 10" Padding="10, 10, 10, 10">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" TextColor = "Black" FontSize = "15"/>
</StackLayout>
<Label Text="This post type is not supported in your current version!" TextColor = "Red" Margin="0, 10, 0, 10" HorizontalOptions="CenterAndExpand" HorizontalTextAlignment="Center"/>
<StackLayout Orientation="Horizontal" Padding="0, 0, 0, 5">
<Label Text="{Binding Likes}" FontSize="15" TextColor="Black" Margin="10, 0, 0, 0"/>
<Image Source="{Binding LikeSource}" HeightRequest = "22" HorizontalOptions = "StartAndExpand"/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
<local:TweetTemplateSelector x:Key="TweetTemplateSelector"
TextPostTemplate="{StaticResource TextPostTemplate}"
InvalidPostTemplate="{StaticResource InvalidPostTemplate}" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content >
<StackLayout BackgroundColor="#1289A7">
<ListView x:Name="PostListView" ItemsSource="{Binding PostObject}"
ItemTemplate="{StaticResource TweetTemplateSelector}" HasUnevenRows="True" />
</StackLayout>
</ContentPage.Content>
然后我使用此代码绑定XML;
public static IList<PostObject> FormatPosts(Page page, INavigation navigation, string json)
{
IList<PostObject> Posts = new List<PostObject>() { };
var posts = JsonConvert.DeserializeObject<List<Post>>(json);
foreach (var post in posts)
{
if (post.type == 0)
{
Posts.Add(new TextPost
{
Name = post.name,
Body = post.body,
Likes = LayoutUtils.FormatCounter(post.Likes),
LikeSource = post.Liked == 1 ? "liked_icon.png" : "like_icon.png"
});
}
else
{
Posts.Add(new InvalidPost
{
Name = post.name,
Likes = LayoutUtils.FormatCounter(post.Likes),
LikeSource = post.Liked == 1 ? "liked_icon.png" : "like_icon.png"
});
}
}
return Posts;
}
答案 0 :(得分:1)
这里有两个选择。