这是我正在处理的对象:
class TopNews
{
public string Id { get; set; }
public string Title { get; set; }
public string ImageURI { get; set; }
public string BodyUri { get; set; }
}
BodyURI 将是一个字符串,其中包含包含 .rtf 文件的 Azure Blob 的地址,例如:https://richeditbox.blob.core.windows。 net/testformat.rtf 是 BodyURI 上可能的字符串。
到目前为止,这是我的 XAML 布局:
<ListView Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image />
<RichEditBox TextWrapping="WrapWholeWords"
IsReadOnly="True"
IsColorFontEnabled="True"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
它缺少很多,但我想做的是将 Azure Blob 存储中的 .rtf 文件的内容绑定(bind)到我的 XAML 布局中的 RichEditBox 控件。
现在,到目前为止,我在这方面所做的所有研究都向我表明,当然,这两者之间必须有一些过程。
我必须为 blob 设置下载:
Uri bloburi = new Uri("https://richeditbox.blob.core.windows.net/testformat.rtf"); CloudBlockBlob cBlob = new CloudBlockBlob(bloburi);我还发现了如何在 RichTextBox 上加载该 .rtf 文件的内容:
richEditBox.Document.SetText(TextSetOptions.FormatRtf, await cBlob.DownloadTextAsync());
我该怎么做?我在想我可以创建一个新类,比如这个:
class TopNewsProcessed
{
public string Id { get; set; }
public string ImageURI { get; set; }
public string Title { get; set; }
public RichEditBox Body { get; set; }
}
这样我就可以运行 .rtf 文件的下载过程,然后将其设置在 RichEditBox 中,但我不知道如何将其绑定(bind)到 RichEditBox 在我的 XAML 布局上。这是一个好主意吗?如果是这样,我该如何绑定(bind)?我是否必须将 Body 从 RichEditBox 更改为其他内容?
请您参考如下方法:
So that I can run the process of download of the .rtf file and then just set it in the RichEditBox, but I have no clue how to approach binding this to the RichEditBox on my XAML layout
创建附加属性 是正确的方向,基于 BabaAndThePigman 在此 link 中提供的解决方案
我为您的场景修改了附加属性:
public class RtfText
{
public static string GetRichText(DependencyObject obj)
{
return (string)obj.GetValue(RichTextProperty);
}
public static void SetRichText(DependencyObject obj, string value)
{
obj.SetValue(RichTextProperty, value);
}
// Using a DependencyProperty as the backing store for RichText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty RichTextProperty =
DependencyProperty.RegisterAttached("RichText", typeof(string), typeof(RtfText), new PropertyMetadata(string.Empty, callback));
private static async void callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var reb = (RichEditBox)d;
Uri bloburi = new Uri((string)e.NewValue);
CloudBlockBlob cBlob = new CloudBlockBlob(bloburi);
var blobstr = await cBlob.DownloadTextAsync();
reb.Document.SetText(TextSetOptions.FormatRtf, blobstr);
}
}
对于Model,不需要改变,保持BodyUri字符串属性即可。
查看:
<ListView ItemsSource="{Binding Data}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Title}" />
<StackPanel Orientation="Horizontal">
<RichEditBox local:RtfText.RichText="{Binding BodyUri}"
TextWrapping="WrapWholeWords"
IsColorFontEnabled="True"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
请注意,在您看来,RichEditBox 的IsReadOnly 属性被设置为“true”,这将导致“访问被拒绝”异常在这一行:RichEditBox.Document.SetText(...)
请查看我在here中完成的 sample
