C# WPF-使用不同颜色显示文本块

C# WPF-使用不同颜色显示文本块,c#,wpf,binding,textblock,C#,Wpf,Binding,Textblock,所以我想做的是显示一个文本块,每行使用不同的颜色,理想情况下我想使用绑定 我的文本块可以显示一个项目列表,每个项目都有文本和颜色属性。对于foreach,我希望使用Texte属性以指定的颜色显示每个项目一行 我已经尝试了以下方法: 1) 我制作了一个TextBlock,它的文本绑定到ViewModel中的字符串属性,我用foreach填充字符串,但在这种情况下,不能按照我的需要在每一行上应用颜色 2) 我发现,在堆栈上,这有点帮助,建议使用运行 因此,在我的ViewModel中,我像这样填充文本

所以我想做的是显示一个文本块,每行使用不同的颜色,理想情况下我想使用绑定

我的文本块可以显示一个项目列表,每个项目都有文本和颜色属性。对于foreach,我希望使用Texte属性以指定的颜色显示每个项目一行

我已经尝试了以下方法:

1) 我制作了一个TextBlock,它的文本绑定到ViewModel中的字符串属性,我用foreach填充字符串,但在这种情况下,不能按照我的需要在每一行上应用颜色

2) 我发现,在堆栈上,这有点帮助,建议使用
运行

因此,在我的ViewModel中,我像这样填充文本块:

private TextBlock legende;
public TextBlock Legende
{
   get { return legende; }
   set
   {
     legende = value;
     this.NotifyPropertyChanged("Legende");
   }
}
public void UpdateLegend(Legend legende)
{
    this.Legende = new TextBlock();
    this.Legende.TextWrapping = TextWrapping.Wrap;
    this.Legende.Margin = new Thickness(10);
    this.Legende.FontSize = 14;
    this.Legende.LineStackingStrategy=LineStackingStrategy.BlockLineHeight;
    this.Legende.LineHeight = 20;
    int i = 0;
    foreach(LegendItem item in legende.list)
    {
      if(i==0)
      {
        Run run = new Run(item.Texte);
        run.Foreground = item.Color;
        this.Legende.Inlines.Add(run);
      }
      else
      {
         Run run = new Run(")\r\n"+item.Texte);
         run.Foreground = item.Color;
         this.Legende.Inlines.Add(run);
      }

      i++;
    }
}
每次我需要更新图例时,我的模型都会执行以下操作:

contexte.UpdateLegend(MonGraphe.Legende);
this.CanvasLegend = contexte.Legende;
那么我的看法是:

<Grid Grid.Column="2" Background="WhiteSmoke">
    <TextBlock x:Name="CanvasLegend" TextAlignment="Left" HorizontalAlignment="Left"/>
</Grid>

现在它根本不起作用,我也不知道为什么。 我还想在ViewModel中执行所有操作,但为此,我需要将Textlock绑定到ViewModel中定义的TextBlock,但找不到如何执行该操作

编辑:

正如Icebat所解释的,我使用的转换器如下:

与IceBat相同的XML

视图模型:

public class ColoringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //is your collection IEnumerable<>? If not, adjust as needed
            var legende = value as Legend;
            if (legende == null) return value;

            return legende.list.Select(i => new Run() { Text = i.Texte, Foreground = i.Color }).ToArray();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    class ViewModelMainWindow : INotifyPropertyChanged
    {
        private Legend legende;
        public Legend Legende
        {
            get { return legende; }
            set
            {
                legende = value;
                this.NotifyPropertyChanged("Legende");
            }
        }
}
公共类ColoringConverter:IValueConverter
{
公共对象转换(对象值、类型targetType、对象参数、CultureInfo区域性)
{
//您的收藏是否可以计算?如果不能,请根据需要进行调整
var legende=图例中的值;
if(legende==null)返回值;
返回legende.list.Select(i=>newrun(){Text=i.Texte,Foreground=i.Color}).ToArray();
}
公共对象转换回(对象值、类型targetType、对象参数、CultureInfo区域性)
{
抛出新的NotImplementedException();
}
}
类ViewModelMainWindow:INotifyPropertyChanged
{
私人传奇莱根德;
公共传奇莱根德
{
获取{return legende;}
设置
{
legende=价值;
本协议。NotifyPropertyChanged(“Legende”);
}
}
}
还包括我的“Legende”课程,因为我认为这是理解错误的地方:

public class LegendItem 
    {
        public int Type { get; set; }
        public double Diametre { get; set; }
        public double Longueur { get; set; }
        public double Profondeur { get; set; }
        public string Texte { get; set; }
        public Brush Color { get; set; }
        public LegendItem()
        {

        }
    }
    public class Legend : INotifyPropertyChanged
    {
        private ObservableCollection<LegendItem> liste;
        public ObservableCollection<LegendItem> Liste
        {
            get { return liste; }
            set
            {
                liste=value;
                NotifyPropertyChanged(ref liste, value);
            }
        }
        public Legend()
        {
            this.list = new ObservableCollection<LegendItem>();
        }
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
        private bool NotifyPropertyChanged<T>(ref T variable, T valeur, [CallerMemberName] string nomPropriete = null)
        {
            if (object.Equals(variable, valeur)) return false;

            variable = valeur;
            NotifyPropertyChanged(nomPropriete);
            return true;
        }
        public Legend(Repere rep)
        {
            List < Brush >  listColors = new List<Brush>();
            listColors.Add(Brushes.Red);
            listColors.Add(Brushes.MediumBlue);
            listColors.Add(Brushes.Purple);
            listColors.Add(Brushes.LimeGreen);
            listColors.Add(Brushes.DarkOrange);
            listColors.Add(Brushes.Navy);
            listColors.Add(Brushes.DarkRed);
            listColors.Add(Brushes.Chartreuse);
            listColors.Add(Brushes.DodgerBlue);
            listColors.Add(Brushes.Tomato);

            this.list = new ObservableCollection<LegendItem>();
            List<Percage> listPer = rep.liste_percages;
            List<GroupePercage> listeGp = rep.listeGpPercages;


            foreach (Percage per in listPer)
            {
                LegendItem itemExists = this.list.FirstOrDefault(x => x.Type == per.Type && x.Diametre == per.Diametre && x.Profondeur == per.Depth&&x.Longueur==per.Longueur);
                if (itemExists == null)
                {
                    LegendItem newItem = new LegendItem();

                    newItem.Type = per.Type;
                    switch (newItem.Type)
                    {
                        case 51: newItem.Texte = "DRILL "; break;
                        case 58: newItem.Texte = "CounterSink "; break;
                        case 59: newItem.Texte = "Tapping "; break;
                        case 12: newItem.Texte = "Slot "; break;
                        default: newItem.Texte = "NOT FOUND "; break;
                    }
                    newItem.Diametre = per.Diametre;
                    newItem.Longueur = per.Longueur;
                    newItem.Texte += newItem.Diametre.ToString();
                    if (newItem.Type==12)
                    {
                        newItem.Texte = newItem.Diametre + " x " + newItem.Longueur;
                    }
                    newItem.Profondeur = per.Depth;
                    this.list.Add(newItem);
                }
            }
            foreach (GroupePercage per in listeGp)
            {
                LegendItem itemExists = this.list.FirstOrDefault(x => x.Type == per.Type && x.Diametre == per.Diametre && x.Profondeur == per.Depth && x.Longueur == per.Longueur);
                if (itemExists == null)
                {
                    LegendItem newItem = new LegendItem();
                    newItem.Type = per.Type;
                    switch (newItem.Type)
                    {
                        case 51: newItem.Texte = "DRILL "; break;
                        case 58: newItem.Texte = "CounterSink "; break;
                        case 59: newItem.Texte = "Tapping "; break;
                        case 12: newItem.Texte = "Slot "; break;
                        default: newItem.Texte = "NOT FOUND "; break;
                    }
                    newItem.Diametre = per.Diametre;
                    newItem.Longueur = per.Longueur;
                    newItem.Texte += newItem.Diametre.ToString();
                    if (newItem.Type == 12)
                    {
                        newItem.Texte = newItem.Diametre + "x" + newItem.Longueur;
                    }
                    newItem.Profondeur = per.Depth;
                    this.list.Add(newItem);
                }
            }
            for(int i=0;i<this.list.Count();i++)
            {
                this.list[i].Color = listColors[Math.Min(i,9)];
            }
        }
    }
公共类LegendItem
{
公共int类型{get;set;}
公共双直径{get;set;}
公共双Longueur{get;set;}
公共双Profondeur{get;set;}
公共字符串Texte{get;set;}
公共笔刷颜色{get;set;}
公共传奇项目()
{
}
}
公共类图例:INotifyPropertyChanged
{
私人可观察收集列表;
公共可观测收集列表
{
获取{return liste;}
设置
{
liste=值;
NotifyPropertyChanged(参考列表,值);
}
}
公共图例()
{
this.list=新的ObservableCollection();
}
公共事件属性更改事件处理程序属性更改;
public void NotifyPropertyChanged(字符串propName)
{
if(this.PropertyChanged!=null)
this.PropertyChanged(this,newpropertyChangedEventArgs(propName));
}
private bool NotifyPropertyChanged(ref T variable,T valeur,[CallerMemberName]字符串nomPropertiete=null)
{
if(object.Equals(variable,valeur))返回false;
变量=valeur;
通知财产变更(非所有权人);
返回true;
}
公共图例(保留代表)
{
列表<画笔>列表颜色=新列表();
listColors.Add(画笔.红色);
listColors.Add(画笔.MediumBlue);
listColors.Add(画笔.紫色);
listColors.Add(笔刷.LimeGreen);
listColors.Add(笔刷.DarkOrange);
listColors.Add(画笔.深蓝色);
listColors.Add(画笔.DarkRed);
listColors.Add(画笔.黄绿色);
listColors.Add(画笔.DodgerBlue);
listColors.添加(画笔.番茄);
this.list=新的ObservableCollection();
List listPer=rep.liste_pertages;
List listeGp=rep.listeGpPercages;
foreach(列表中的百分比)
{
LegendItemExists=this.list.FirstOrDefault(x=>x.Type==per.Type&&x.Diametre==per.Diametre&&x.Profondeur==per.Depth&&x.Longueur==per.Longueur);
如果(itemExists==null)
{
LegendItem newItem=新LegendItem();
newItem.Type=per.Type;
开关(newItem.Type)
{
案例51:newItem.Texte=“DRILL”中断;
案例58:newItem.Texte=“CounterSink”中断;
案例59:newItem.Texte=“Tapping”中断;
案例12:newItem.Texte=“Slot”中断;
默认值:newItem.Texte=“未找到”中断;
}
新项目直径=每直径;
newItem.Longueur=per.Longueur;
newItem.Texte+=newItem.Diametre.ToString();
if(newItem.Type==12)
{
newItem.Texte=newItem.Diametre+“x”+newItem.Longueur;
}
newItem.Profondeur=每深度;
this.list.Add(newItem);
}
}
foreach(每个列表中的组百分比)
{
LegendItemExists=this.list.FirstOrDefault(x=>x.Type==per.Type&&x.Diametre==per.Diametre&&x.Profondeur==per.Depth&&x.Longueur==per.Longueur);
如果(itemExists==null)
{
LegendItem newItem=新LegendItem();
<TextBlock x:Name="CanvasLegend" TextAlignment="Left" HorizontalAlignment="Left">
    <TextBlock.Inlines>
        <ItemsControl ItemsSource="{Binding LegendItems, ElementName=me, 
                                    Converter={StaticResource coloringConverter}}" />
    </TextBlock.Inlines>
</TextBlock>
public class ColoringConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
     //is your collection IEnumerable<>? If not, adjust as needed
     var legend = value as IEnumerable<LegendItem>;
     if (legend == null) return value;

     return legend.Select(i => new Run() { Text = i.Text, Foreground = i.Color }).ToArray();
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
     throw new NotImplementedException();
  }
}
<Window.Resources>
    <local:ColoringConverter x:Key="coloringConverter" />
</Window.Resources>