简体   繁体   English

c#listview中的多种颜色(wpf)

[英]c# multiple colors in listview (wpf)

I making a listview in WPF and I want that it will display some items with multiple colors (example: http://i.stack.imgur.com/Xi43d.png ).我在 WPF 中制作了一个列表视图,我希望它会显示一些具有多种颜色的项目(例如: http : //i.stack.imgur.com/Xi43d.png )。
This is my listview with the columns:这是我的列列表视图:

<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>

I add the items with this code:我使用以下代码添加项目:

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; }
}

I want to find a way that I can make a text like that: ^2Gun^3Money and it will display in diffrent colors(the ^2 say which color)我想找到一种方法来制作这样的文本:^2Gun^3Money 它将以不同的颜色显示(^2 表示哪种颜色)

As I can understand, you need some mechanism that translate the string ^2Gun^3Money to string color pairs collection and display this in data grid cell.据我所知,您需要某种机制将字符串 ^2Gun^3Money 转换为字符串颜色对集合并将其显示在数据网格单元格中。 If so here some solution of that problem: 1. XAML code:如果是这样,这里有一些该问题的解决方案: 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>

Explanation;解释; 1) ServerNameCellTemplate is the data grid cell's template. 1) ServerNameCellTemplate 是数据网格单元格的模板。 This is a list box that displays the part of the name in a text block and define the text block brush based on provided key.这是一个列表框,在文本块中显示名称的一部分,并根据提供的键定义文本块画笔。 2)ServerNameString2ColorNamePartValuesConverter converts the provided string to partial name and its brush objects. 2)ServerNameString2ColorNamePartValuesConverter 将提供的字符串转换为部分名称及其画笔对象。 3)ColorValuePairs available colors. 3)ColorValuePairs 可用颜色。 2. ViewModel code (provide the ListView ItemsSource): 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. Server model: 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. Converters and its models: 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 is the simple implementation of INotifyPropertyChanged interface. 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;
    }
}

The solution is provided by converters that converts the string to object that we can template in xaml.该解决方案由转换器提供,该转换器将字符串转换为我们可以在 xaml 中模板化的对象。 I hope it will help you.我希望它会帮助你。 Regards,问候,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM