在自定义Textblock中将文本的一部分加粗会破坏绑定

时间:2017-05-04 11:29:47

标签: wpf

我正在努力制作一部分文字为"粗体"但在执行此绑定后,中断和正确的文本值不会反映在TextBlock

我使用的TextBlock是自定义的,以下是用于使文本变为粗体的代码块

XAML代码

 <StackPanel Margin="10" Grid.Row="0" Grid.Column="0">
        <ComboBox ItemsSource="{Binding ListNames}" SelectedItem="{Binding MySelectedItem}">
        </ComboBox>
    </StackPanel>
    <StackPanel Grid.Row="1" Grid.Column="0">
        <controls:TrimmedToolTipTextBlock Name="txbInfoText" TextWrapping="Wrap" Visibility="Visible"
                                          controls:TextBlockFormatter.FormattedText="{Binding Text, ElementName=txbInfoText}"
               Margin="10,0,0,0" 
               FontSize="13" TextAlignment="Center">
            <TextBlock.Text>
                <MultiBinding Converter="{StaticResource StringFormatConverter}">
                    <localization:Localize Key="Message"/>
                    <Binding Path="Name" IsAsync="True" />
                    <Binding Path="Address"/>
                    <Binding Path="City"/>
                </MultiBinding>
            </TextBlock.Text>
        </controls:TrimmedToolTipTextBlock>
    </StackPanel>

在这个代码块中我有一个组合框和自定义TrimmedToolTipTextBlock,在更改组合框中的选定项时,textblock中的值应相应更改。消息值来自资源文件,它接受Name,Address和City作为参数和部分消息文本位于 标记内。

CS代码块

public static readonly DependencyProperty FormattedTextProperty =
        DependencyProperty.RegisterAttached("FormattedText", typeof(string), typeof(TextBlockFormatter),
        new PropertyMetadata(string.Empty, (sender, e) =>
        {
            string text = e.NewValue as string;

            if (!text.Contains("<b>"))
                return;

            var textBlock = sender as TextBlock;
            if (textBlock != null)
            {
                textBlock.Inlines.Clear();
                var tags = text.Split(new string[] { "<b>", "</b>" }, StringSplitOptions.None);
                for (int i = 0; i < tags.Length; i++)
                {
                    if (!string.IsNullOrWhiteSpace(tags[i]))
                        textBlock.Inlines.Add(new Run { Text = tags[i], FontWeight = i % 2 == 1 ? FontWeights.Bold : FontWeights.Normal });

                }
            }
        }));

在此代码块中,我将识别 标记内的部分文本,并将其字体粗细更改为粗体。

1 个答案:

答案 0 :(得分:0)

不确定,但我想如果将MultiBinding直接分配给附加属性,它应该可以工作:

class DayMealType extends DataObject
{
     private static $db = array(
        'Calories'  => 'Int',
        'Carbohydrates'  => 'Int',
        'Proteins'  => 'Int',
        'Lipids'  => 'Int',
        'Price' => 'Decimal'
     );

      private static $has_one = array(
        "MealType" => "MealTypeDetails",
        "DayDietMealPlan" => "DayDietMealPlan"
      );
      private static $many_many = array(
        "Foods" => "FoodMealPlan"
      );

      private static $casting = array(
        'FoodsList' => 'HTMLText'
      );