首页 新闻 搜索 专区 学院

在ListBox中使用RichTextBox,如何实现RichTextBox绑定数据

0
悬赏园豆:100 [已解决问题] 解决于 2013-10-27 10:59

我想把RichTextBox当做ListBox 的Item来用,可是怎么才能实现RichTextBox的数据绑定呢

????在线等答案!!!

御风不败的主页 御风不败 | 初学一级 | 园豆:66
提问于:2013-10-26 17:13
< >
分享
最佳答案
1

要结贴了,我最后的解决方案是重写了RichTextBox,代码如下:

 public class RichTextBlock : System.Windows.Controls.RichTextBox     {         public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(RichTextBlock), new PropertyMetadata(OnBlockTextChanged));

        private string[] FaceName = { "[发红包]", "[兔子]", "[熊猫]", "[给力]" };

        public string Text         {             get { return (string)GetValue(TextProperty); }             set { SetValue(TextProperty, value); SetLinkedText(value); }         }

        static void OnBlockTextChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)         {             if (obj != null && obj is RichTextBlock)             {                 //(obj as RichTextBlock).SetLinkedText((string)e.NewValue);                 (obj as RichTextBlock).SetFaceText((string)e.NewValue);             }         }

        public void SetLinkedText(string htmlFragment)         {             var regEx = new Regex(                 @"\<a\s(href\=""|[^\>]+?\shref\="")(?<link>[^""]+)"".*?\>(?<text>.*?)(\<\/a\>|$)",                 RegexOptions.IgnoreCase | RegexOptions.Multiline);

            this.Blocks.Clear();

            int nextOffset = 0;

            foreach (Match match in regEx.Matches(htmlFragment))             {                 if (match.Index > nextOffset)                 {                     this.AppendText(htmlFragment.Substring(nextOffset, match.Index - nextOffset));                     nextOffset = match.Index + match.Length;                     this.AppendLink(match.Groups["text"].Value, new Uri(match.Groups["link"].Value));                 }

            }

            if (nextOffset < htmlFragment.Length)             {                 this.AppendText(htmlFragment.Substring(nextOffset));             }         }

        public void SetFaceText(string faceText)         {             //ObservableCollection<FaceItem> faceItemList = new ObservableCollection<FaceItem>();                   //FaceItem item1 = new FaceItem { FaceName = "[disdain]", FaceUri = "Emotions/[disdain].png" };                      //FaceItem item2 = new FaceItem { FaceName = "[joyful]", FaceUri = "Emotions/[joyful].png" };                    //faceItemList.Add(item1);             //faceItemList.Add(item2);                      //this.FaceList.ItemsSource = faceItemList;

            char[] abcs = faceText.ToCharArray();           //将需要转换的内容转换成char数组,便于我们进行筛选操作,例如:“大家好,hello,希望大家喜欢[disdain],开心哦[joyful]哈哈哈!”             string strs = "";                          //文字(非"[]"类型的文字)  例如:“大家好,hello,希望大家喜欢”             string strface = "";                       //图片("[]"类型的文字)    例如:“[disdain]”             List<string> list = new List<string>();    //我们把文字和图片放入其中,最后我们通过遍历这个list来动态为richbox添加内容             for (int i = 0; i < abcs.Count(); i++)             {                 if (abcs[i].ToString() != "[")                 {                     for (int j = 0; j < abcs.Count() - i; j++)                     {                         if (abcs[i + j].ToString() != "[")                         {                             strs = strs + abcs[i + j].ToString();                             if (i + j == abcs.Count() - 1)                             {                                 if (abcs[i + j].ToString() != "]")                                 {                                     i = i + j;                                     break;                                 }                             }                         }                         else                         {                             i = i + j - 1;                             break;                         }

                    }                     if (strs != "")                     {                         list.Add(strs);                         strs = "";                     }                 }                 if (abcs[i].ToString() == "[")                 {                     for (int j = 0; j < abcs.Count() - i; j++)                     {                         if (abcs[i + j].ToString() != "]")                         {                             strface = strface + abcs[i + j].ToString();

                        }                         if (abcs[i + j].ToString() == "]")                         {                             strface = strface + abcs[i + j].ToString();                             i = i + j;                             break;                         }

                    }                     //FaceItem itemnew = new FaceItem { FaceName = strface, FaceUri = "Emotions/" + strface + ".png" };                     if (true)                     {                         list.Add(strface);                         strface = "";

                    }                 }             }

            //// 动态生成richbox内的内容             Paragraph ph = new Paragraph(); //放到for循环外面,因为只有一个段落就够了             this.Blocks.Add(ph);        //放入到richbox中             for (int i = 0; i < list.Count(); i++)             {                 if (list[i].ToString().StartsWith("["))                 {                     // Run myRun= new Run();                     InlineUIContainer iu = new InlineUIContainer();                     Image im = new Image();                     for (int j = 0; j < FaceName.Length; j++)                     {                         if (FaceName[j] == list[i].ToString())                         {                             if (j < 10)                             {                                 im.Source = new BitmapImage(new Uri("/Face/" + "a00"+(j+1) + ".png", UriKind.RelativeOrAbsolute));                                 Debug.WriteLine("/Face/" + "a00" + j + ".png");                             }                             else if (j < 100)                             {                                 im.Source = new BitmapImage(new Uri("/Face/" + "a0" + (j + 1) + ".png", UriKind.RelativeOrAbsolute));                                 Debug.WriteLine("/Face/" + "a0" + j + ".png");                             }                             else                             {                                 im.Source = new BitmapImage(new Uri("/Face/" + "a" + (j + 1) + ".png", UriKind.RelativeOrAbsolute));                                 Debug.WriteLine("/Face/" + "a" + j + ".png");                             }                                                    }                     }                                         im.Height = 40;                     iu.Child = im;

                    ph.Inlines.Add(iu);                 }                 else                 {                     Run myRun = new Run();                     myRun.Text = list[i].ToString();                     ph.Inlines.Add(myRun);

                }

            }         }

        public void AppendText(string text)         {             Paragraph paragraph;

            if (this.Blocks.Count == 0 ||                 (paragraph = this.Blocks[this.Blocks.Count - 1] as Paragraph) == null)             {                 paragraph = new Paragraph();                 this.Blocks.Add(paragraph);             }

            paragraph.Inlines.Add(new Run { Text = text });         }

        public void AppendLink(string text, Uri uri)         {             Paragraph paragraph;

            if (this.Blocks.Count == 0 ||                 (paragraph = this.Blocks[this.Blocks.Count - 1] as Paragraph) == null)             {                 paragraph = new Paragraph();                 this.Blocks.Add(paragraph);             }

            var run = new Run { Text = text };             var link = new Hyperlink { NavigateUri = uri };

            link.Inlines.Add(run);             paragraph.Inlines.Add(link);         }     }

御风不败 | 初学一级 |园豆:66 | 2013-10-27 10:57
其他回答(2)
0

RichTextBox.Text不能赋值??

何以解忧唯有撸码 | 园豆:368 (菜鸟二级) | 2013-10-26 17:19

大哥,RichTextBox根本就没有.text属性的好不好啊

支持(0) 反对(0) 御风不败 | 园豆:66 (初学一级) | 2013-10-26 17:21

@御风不败: 你把我吓尿了,RichTextBox没有Text属性?? 吓的我刚打开VS 建个项目来测试! 你是winform还是什么?

支持(0) 反对(0) 何以解忧唯有撸码 | 园豆:368 (菜鸟二级) | 2013-10-26 17:25

@御风不败: 兄弟,我也在线给你回答问题呢。。求速度问。 我都刷新好多次了

支持(0) 反对(0) 何以解忧唯有撸码 | 园豆:368 (菜鸟二级) | 2013-10-26 17:33

@康忠鑫-Stephen: Windows Phone项目

支持(0) 反对(0) 御风不败 | 园豆:66 (初学一级) | 2013-10-26 17:34

@康忠鑫-Stephen: 不管组后能不能解决问题,还是要先谢谢您了

支持(0) 反对(0) 御风不败 | 园豆:66 (初学一级) | 2013-10-26 17:35

@御风不败: WP 不懂,不客气

支持(0) 反对(0) 何以解忧唯有撸码 | 园豆:368 (菜鸟二级) | 2013-10-26 17:36
0

xaml code:

<ListBox Margin="0,0,-12,0" Name="userDrops">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Margin="0,0,0,17" Width="432">
                            <RichTextBox>
                                <Paragraph>
                                    <Run Text="{Binding Body}" FontSize="25" FontFamily="Segoe WP"></Run>
                                </Paragraph>
                                <Paragraph>
                                    <Run Text="{Binding Created}" FontFamily="Segoe WP SemiLight"></Run>
                                </Paragraph>
                            </RichTextBox>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

c# code:

var data = from query in loadedData.Descendants("item")
                   select new droppedItem
                   {
                       Id = (int)query.Element("id"),
                       Body = (string)query.Element("body"),
                       Created = (DateTime)ConvertFromUnixTimestamp((double)query.Element("created"))
                   };
        userDrops.ItemsSource = data;

你要是有复杂类型的,就需要写一个在自己的转换器了,可以参考这个:

http://stackoverflow.com/questions/10135984/windows-phone-7-dynamic-listbox-template

收获园豆:100
悟行 | 园豆:12240 (专家六级) | 2013-10-26 21:39

我想说的是,我用RichTextBox是为了能够实现表情和文本混排的那种效果,这个恐怕解决不了我的问题,不过还是要谢谢你了,在昨天晚上我已经解决了!!!

支持(0) 反对(0) 御风不败 | 园豆:66 (初学一级) | 2013-10-27 10:53
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册