c#列表视图中的多种颜色(wpf)

本文关键字:颜色 wpf 列表 视图 | 更新日期: 2023-09-27 18:21:56

我在WPF中创建了一个列表视图,我希望它能用多种颜色显示一些项目(例如:https://i.stack.imgur.com/Xi43d.png)
这是我的列列表视图:

<ListView x:Name="listView" Margin="0,27,0,0">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Server Name" DisplayMemberBinding="{Binding ServerName}"/>
                <GridViewColumn Header="Players" DisplayMemberBinding="{Binding Players}"/>
                <GridViewColumn Header="Map" DisplayMemberBinding="{Binding Map}"/>
                <GridViewColumn Header="Game Type" DisplayMemberBinding="{Binding GameType}"/>
                <GridViewColumn Header="Ip" DisplayMemberBinding="{Binding Ip}"/>
            </GridView>
        </ListView.View>
    </ListView>

我用这个代码添加项目:

listView.Items.Add(new Server { ServerName = "GunMoney", Players = "0/16", Map = "ut4_asd", GameType = "FFA", Ip = "127.0.0.0:27960" });
public class Server
{
    public string ServerName { get; set; }
    public string Players { get; set; }
    public string Map { get; set; }
    public string GameType { get; set; }
    public string Ip { get; set; }
}

我想找到一种方法,我可以制作这样的文本:^2Gun^3Money,它将以不同的颜色显示(^2表示哪种颜色)

c#列表视图中的多种颜色(wpf)

正如我所理解的,您需要一些机制来将字符串^2Gun^3Money转换为字符串颜色对集合,并将其显示在数据网格单元中。如果是这样的话,这里有这个问题的一些解决方案:1.XAML代码:

<Window x:Class="SoGridViewHelpAttempt.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:soGridViewHelpAttempt="clr-namespace:SoGridViewHelpAttempt"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <DataTemplate x:Key="ServerNameCellTemplate" DataType="soGridViewHelpAttempt:ServerNameObject">
        <ListBox ItemsSource="{Binding ServerNamePartsCollection}" BorderBrush="#00000000" BorderThickness="2">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"></StackPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate DataType="soGridViewHelpAttempt:ServerNameParts">
                                <TextBlock IsHitTestVisible="False" Text="{Binding NamePart}" Background="{Binding NamePartBrush}"></TextBlock>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>
    </DataTemplate>
    <x:Array x:Key="ColorValuePairs" Type="soGridViewHelpAttempt:ColorAndKey">
        <soGridViewHelpAttempt:ColorAndKey Key="^1" Brush="Red"/>
        <soGridViewHelpAttempt:ColorAndKey Key="^2" Brush="Green"/>
        <soGridViewHelpAttempt:ColorAndKey Key="^3" Brush="Blue"/>
    </x:Array>
    <soGridViewHelpAttempt:ServerNameString2ColorNamePartValuesConverter x:Key="ServerNameString2ColorNamePartValuesConverterKey" BrushMap ="{StaticResource ColorValuePairs}"/>
</Window.Resources>
<Window.DataContext>
    <soGridViewHelpAttempt:DataGridMAinViewModel/>
</Window.DataContext>
<Grid>
    <ListView x:Name="ListView" Margin="0,27,0,0" ItemsSource="{Binding ServerDataCollection}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Server Name">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate DataType="soGridViewHelpAttempt:Server">
                            <ContentControl x:Name="ServerNamePresenter" Content="{Binding ServerName, Converter={StaticResource ServerNameString2ColorNamePartValuesConverterKey}}" ContentTemplate="{StaticResource ServerNameCellTemplate}"></ContentControl>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Players" DisplayMemberBinding="{Binding Players}"/>
                <GridViewColumn Header="Map" DisplayMemberBinding="{Binding Map}"/>
                <GridViewColumn Header="Game Type" DisplayMemberBinding="{Binding GameType}"/>
                <GridViewColumn Header="Ip" DisplayMemberBinding="{Binding Ip}"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

解释1) ServerNameCellTemplate是数据网格单元格的模板。这是一个列表框,用于显示文本块中的名称部分,并根据提供的键定义文本块画笔。2) ServerNameString2ColorNamePartValuesConverter将提供的字符串转换为部分名称及其笔刷对象。3) ColorValuePairs可用颜色。2.ViewModel代码(提供ListView ItemsSource):

  public class DataGridMAinViewModel:BaseObservableObject
{
    public DataGridMAinViewModel()
    {
        ServerDataCollection = new ObservableCollection<Server>(new List<Server>
        {
            new Server { 
                ServerName = "^1Gun^3Money",
            Players = "0/16", Map = "ut4_asd", GameType = "FFA", Ip = "127.0.0.0:27960" },
             new Server { ServerName = "^2Gun^1Money",
            Players = "0/16", Map = "ut4_asd", GameType = "FFA", Ip = "127.0.0.0:27960" },
             new Server { ServerName = "^2Gun^3Money",
            Players = "0/16", Map = "ut4_asd", GameType = "FFA", Ip = "127.0.0.0:27960" },
        });
    }
    public ObservableCollection<Server> ServerDataCollection { get; set; }
}

3.服务器型号:

public class Server:BaseObservableObject
{
    private string _serverName;
    private string _players;
    private string _map;
    private string _gameType;
    private string _ip;
    public string ServerName
    {
        get { return _serverName; }
        set
        {
            _serverName = value;
            OnPropertyChanged();
        }
    }
    public string Players
    {
        get { return _players; }
        set
        {
            _players = value;
            OnPropertyChanged();
        }
    }
    public string Map
    {
        get { return _map; }
        set
        {
            _map = value;
            OnPropertyChanged();
        }
    }
    public string GameType
    {
        get { return _gameType; }
        set
        {
            _gameType = value;
            OnPropertyChanged();
        }
    }

    public string Ip
    {
        get { return _ip; }
        set
        {
            _ip = value;
            OnPropertyChanged();
        }
    }
}

4.转换器及其型号:

    public class ServerNameString2ColorNamePartValuesConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var name = value.ToString();
        var verbalNameParts = name.Split(BrushMap.Select(item => item.Key).ToArray(), StringSplitOptions.RemoveEmptyEntries);
        var colorKeyNameParts = name.Split(verbalNameParts, StringSplitOptions.RemoveEmptyEntries);
        if (verbalNameParts.Length != colorKeyNameParts.Length) return null;
        var index = 0;
        var nameMappedToColors = new ObservableCollection<ServerNameParts>();
        verbalNameParts.ToList().ForEach(namePart =>
        {
            var brush = BrushMap.FirstOrDefault(item => item.Key == colorKeyNameParts[index]);
            if(brush == null) return;
            nameMappedToColors.Add(new ServerNameParts
           {
               NamePart = namePart,
               NamePartBrush = brush.Brush,
           });
            index++;
        });
        return new ServerNameObject{ServerNamePartsCollection = nameMappedToColors};
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
    public ColorAndKey[] BrushMap { get; set; }
}
public class ColorAndKey
{
    public string Key { get; set; }
    public Brush Brush { get; set; }
}
public class ServerNameObject : BaseObservableObject
{
    public ObservableCollection<ServerNameParts> ServerNamePartsCollection { get; set; }
}
public class ServerNameParts : BaseObservableObject
{
    private string _name;
    private Brush _namePartBrush;

    public Brush NamePartBrush
    {
        get { return _namePartBrush; }
        set
        {
            _namePartBrush = value;
            OnPropertyChanged();
        }
    }
    public string NamePart
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged();
        }
    }
}

5.BaseObservableObject是INotifyPropertyChanged接口的简单实现。

public class BaseObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected virtual void OnPropertyChanged<T>(Expression<Func<T>> raiser)
    {
        var propName = ((MemberExpression)raiser.Body).Member.Name;
        OnPropertyChanged(propName);
    }
    protected bool Set<T>(ref T field, T value, [CallerMemberName] string name = null)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(name);
            return true;
        }
        return false;
    }
}

该解决方案由转换器提供,该转换器将字符串转换为我们可以在xaml中模板化的对象。我希望它能帮助你。问候,