2016-01-26 2 views
1

У меня есть MultiValueConverter и нужны «значения», чтобы быть полужирным, когда они введены в приложение. Ниже мой код. Есть ли что-то, что я могу добавить в код, чтобы сделать все значения жирным? ThanksКак стиль значений в конвертере?

class FlightConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (values != null) 
     { 
      return "Outbound flight from " + values[0] + " to " + values[1] + " departing at " + values[2] + 
        " with " + values[3] + " in " + values[4]; 
     } 

     return " "; 
    } 
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) 
    { 
     string[] values = null; 
     if (value != null) 
      return values = value.ToString().Split(' '); 
     return values; 
    } 
} 
+0

ChrisF не говорит об этом напрямую, но это неправильное использование для конвертера. – slugster

ответ

2

Вы не сможете сделать этого в течение одного TextBlock.

Самым простым решением было бы изменить код XAML, так что вы связываете пять значений, чтобы отделить текстовые блоки, которые вы можете индивидуально стиль:

<StackPanel Orientation="Horizontal"> 
    <TextBlock Text="Outbound flight from " /> 
    <TextBlock Text="{Binding value0}" FontWeight="Bold" /> 
    <TextBlock Text=" to " /> 
    <TextBlock Text="{Binding value1}" FontWeight="Bold" /> 
    <TextBlock Text=" departing at " /> 
    <TextBlock Text="{Binding value2}" FontWeight="Bold" /> 
    <TextBlock Text=" with " /> 
    <TextBlock Text="{Binding value3}" FontWeight="Bold" /> 
    <TextBlock Text=" in " /> 
    <TextBlock Text="{Binding value4}" FontWeight="Bold" /> 
</StackPanel> 

Другим способом было бы использовать RichTextBox и создать текст из серии Runs или привязать Runs к вашим свойствам.

+0

Я не думаю, что вы можете связать документ с RichTextBox – Paparazzi

+0

@Frisbee - я никогда не предполагал, что вы могли. – ChrisF

1

После того, как вы его видите, вы не хотите, чтобы сделать это
текста является Привязываемым к TextBlock, но встраивает не Привязываемое
Так что вам нужно наращивать Внутристрочные с преобразователем

Рассмотрим FlowDocument и один из зрителя FlowDoument

Или просто сделать это как ответ от ChrisF

Bind к содержательному контролю

[ValueConversion(typeof(string), typeof(object))] 
    public sealed class StringToXamlConverter : IValueConverter 
    { 
     /// <summary> 
     /// Converts a string containing valid XAML into WPF objects. 
     /// </summary> 
     /// <param name="value">The string to convert.</param> 
     /// <param name="targetType">This parameter is not used.</param> 
     /// <param name="parameter">This parameter is not used.</param> 
     /// <param name="culture">This parameter is not used.</param> 
     /// <returns>A WPF object.</returns> 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      string input = value as string; 
      if (!string.IsNullOrEmpty(input)) 
      { 
       string escapedXml = SecurityElement.Escape(input); 
       string withTags = escapedXml.Replace("|~S~|", "<Run Style=\"{DynamicResource highlight}\">"); 
       withTags = withTags.Replace("|~E~|", "</Run>"); 

       //withTags = withTags.Replace("\r\n","&#13;\n"); 

       string wrappedInput = string.Format("<TextBlock xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TextWrapping=\"Wrap\">{0}</TextBlock>", withTags); 

       using (StringReader stringReader = new StringReader(wrappedInput)) 
       { 
        try 
        { 
         using (XmlReader xmlReader = XmlReader.Create(stringReader)) 
         { 
          return XamlReader.Load(xmlReader); 
         } 
        } 
        catch (Exception Ex) 
        { 
         Debug.WriteLine("StringToXamlConverter Exception " + Ex.Message); 
         Debug.WriteLine("input = " + input); 
         Debug.WriteLine("escapedXml = " + escapedXml); 
         Debug.WriteLine("withTags = " + withTags); 
         Debug.WriteLine("wrappedInput = " + wrappedInput); 
         if (App.StaticGabeLib.CurUserP.IsInRoleSysAdmin && false) 
         { 
          throw new Exception("StringToXamlConverter. Only sysAdmin gets this error - for other users the error is swallowed. " + input + " " + Ex.Message); 
         } 
         else 
         { 
          return input; 
         } 
        } 
       } 
      } 
      return null; 
     } 

     /// <summary> 
     /// Converts WPF framework objects into a XAML string. 
     /// </summary> 
     /// <param name="value">The WPF Famework object to convert.</param> 
     /// <param name="targetType">This parameter is not used.</param> 
     /// <param name="parameter">This parameter is not used.</param> 
     /// <param name="culture">This parameter is not used.</param> 
     /// <returns>A string containg XAML.</returns> 
     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      throw new NotImplementedException("This converter cannot be used in two-way binding."); 
     } 
    } 
Смежные вопросы