如何在WPF中更改DataGrid单元格内部分字符串的前景色?

mrphzbgm  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(182)

这是我的主窗口。xaml**

<Window x:Class="Helloone.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Helloone"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="DG1" Margin="0,100,0,0" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="text1" Binding="{Binding Onedata}" Width="150"/>
                <DataGridTextColumn Header="text2" Binding="{Binding Twodata}" Width="150"/>
                
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

这是我的主窗口。xaml.cs

namespace Helloone
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            List<MyCell> listaaa = new List<MyCell>();
            listaaa.Add(new MyCell() { Onedata="abc", Twodata ="def"});
            listaaa.Add(new MyCell() { Onedata="ghj", Twodata ="yougood"});
            DG1.ItemsSource= listaaa;
        }
    }

    public class MyCell
    {
        public string? Onedata { get; set; }
        public string? Twodata { get; set; }
    }
}

运行后如下enter image description here
我想改变其中一个单元格中的一些字符串的颜色,并使它们变粗。比如第二行第二列的字符串“yougood”中的“good”设置为红色加粗,而“you”的颜色保持不变,运行后的效果如下图

enter image description here

由于我的母语不是英语,我很难搜索,好心人请帮助我

1szpjjfi

1szpjjfi1#

使用TextBlock设置文本的内联格式。看看这个:Formatting text in a TextBlock
代码隐藏:

private Run GetGoodRun()
{
    return new Run("good")
    {
        Foreground = new SolidColorBrush(Colors.Red),
        FontWeight = FontWeights.Bold,
    };
}

private void FormatText(TextBlock tb, string text)
{
    if (string.IsNullOrEmpty(text) || !text.Contains("good"))
        return;

    var tokens = text.Split("good");
    for (int i = 0; i < tokens.Length - 1; i++)
    {
        tb.Inlines.Add(tokens[i]);
        tb.Inlines.Add(GetGoodRun());
    }

    tb.Inlines.Add(tokens.LastOrDefault());
}

private void TextBlock_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    FormatText(sender as TextBlock, (e.NewValue as MyCell)?.Twodata);
}

XAML:

<DataGridTemplateColumn Header="text2"
                        Width="150">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Twodata}"
                       DataContextChanged="TextBlock_DataContextChanged" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
yb3bgrhw

yb3bgrhw2#

首先你需要知道红色和粗体部分在字符串中的位置。之后,您可以使用TextBlock和DataTempalte来显示字符串的各个部分。字符串被分成三部分。红色的部分,红色之前和之后的部分。

public partial class MainWindow : Window
    {
        public string redpart = "good";
        public MainWindow()
        {
            InitializeComponent();
            List<MyCell> listaaa = new List<MyCell>();
            listaaa.Add(new MyCell() { Onedata = "abc", Twodata = "def" });
            listaaa.Add(new MyCell() { Onedata = "ghj", Twodata = "yougood" });
            listaaa.Add(new MyCell() { Onedata = "lmn", Twodata = "goodbye" });
            DG1.ItemsSource = listaaa;

            foreach (var cell in listaaa)
            {
                if (cell.Twodata != null)
                {
                    int index = cell.Twodata.IndexOf(redpart);
                    if (index >= 0)
                    {
                        cell.TwodataBeforeRedPart = cell.Twodata.Substring(0, index);
                        cell.TwodataRedPart = cell.Twodata.Substring(index, redpart.Length);
                        cell.TwodataAfterRedPart = cell.Twodata.Substring(index + redpart.Length);
                    }
                    else
                    {
                        cell.TwodataBeforeRedPart = cell.Twodata;
                        cell.TwodataRedPart = "";
                        cell.TwodataAfterRedPart = "";
                    }
                }
            }
        }
    }

我将属性添加到MyCell,但您也可以在其他地方处理它。

public class MyCell
   {
       public string? Onedata { get; set; }
       public string? Twodata { get; set; }
       public string TwodataBeforeRedPart { get; set; }
       public string TwodataRedPart { get; set; }
       public string TwodataAfterRedPart { get; set; }
   }

以下是更新的网格

<Grid>
        <DataGrid x:Name="DG1" Margin="0,100,0,0" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="text1" Binding="{Binding Onedata}" Width="150"/>
                <DataGridTemplateColumn Header="text2">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock>
                                <Run Text="{Binding TwodataBeforeRedPart}" />
                                <Run FontWeight="Bold" Foreground="Red" Text="{Binding TwodataRedPart}" />
                                <Run Text="{Binding TwodataAfterRedPart}" />
                            </TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>

相关问题