C# 和 XAML 中的多种格式类型列表视图 [英] Multiple format types listview in C# and XAML
问题描述
我正在创建一个带有显示消息对象的列表视图的消息传递应用程序.
当新用户加入时,我想添加(例如)约翰加入",但我希望它的格式与消息不同.
我怎样才能做到这一点?
对于这种情况,您可以实施
I am creating a messaging application with a listview that displays message objects.
When a new user joins, I want to add (for example) "John joined" but I want it to be formatted differently than a message.
How can I achieve this?
For this scenario, you can implement the ItemsControl.ItemTemplateSelector property of the ListView
.
For example, create a class inherit from DataTemplateSelector
first like this:
public class MessageDataTemplateSelecotr : DataTemplateSelector
{
public DataTemplate NormalTemplate { get; set; }
public DataTemplate JoinedTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
var message = item as MessageModel;
if (message.MessageType.ToString() == "Normal")
return NormalTemplate;
else
return JoinedTemplate;
}
}
Then you can use this selector for example like this:
<Page.Resources>
<DataTemplate x:Key="NormalMessageTemplate">
<TextBlock Text="{Binding Message}" FontSize="20" Foreground="Blue"/>
</DataTemplate>
<DataTemplate x:Key="JoinedMessageTemplate">
<TextBlock Text="{Binding Message}" FontSize="15" Foreground="Red"/>
</DataTemplate>
<local:MessageDataTemplateSelecotr x:Key="MessageDataTemplateSelecotr"
NormalTemplate="{StaticResource NormalMessageTemplate}"
JoinedTemplate="{StaticResource JoinedMessageTemplate}"/>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView ItemTemplateSelector="{StaticResource MessageDataTemplateSelecotr}" ItemsSource="{x:Bind listViewCollection}"/>
</Grid>
In the code behind just add data into the listViewCollection
like this:
ObservableCollection<MessageModel> listViewCollection = new ObservableCollection<MessageModel>();
private enum _MessageType
{
Normal,
Joined
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
listViewCollection.Add(new MessageModel { Message = "hello world!", MessageType = _MessageType.Normal });
listViewCollection.Add(new MessageModel { Message = "John joined", MessageType = _MessageType.Joined });
}
And my MessageModel
class is like this:
public class MessageModel
{
public string Message { get; set; }
public Enum MessageType { get; set; }
}
The rendering image of this ListView
is here:
这篇关于C# 和 XAML 中的多种格式类型列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!