[wpf]请教如何控制自定义类的xaml序列化节点

kevin2y 2019-03-07 04:56:07
我有一个自定义的InlineImage 类,会利用设置的base64字符串在界面上显示一个Image,类似这样:

FlowDocument doc = new FlowDocument();
InlineImage img = new InlineImage();
img.Width = 20;
img.Height = 20;
img.Base64Source = base64String;
doc.Blocks.Add(img);

显示没有问题,但我还想将其做为xaml保存起来,使用以下代码

string xaml = XamlWriter.Save(doc);

得到的xaml是这样的,
<!--省略部分头部内容-->
<rttac:InlineImage Width="20" Height="20">
<rttac:InlineImage.Child>
<Image Stretch="Uniform" StretchDirection="Both" Width="20" Height="20">
<Image.Source><BitmapImage BaseUri="{x:Null}" /></Image.Source>
</Image>
</rttac:InlineImage.Child>
iVBORw0KGg....3a8EQn3QQbWI19U6FxOyJ39qGQL5gZKkYSJBgCCwHM++f/SXAxaJ43MKIgotUYkaeixRiBF9BaAn4Carbq4WinWykAAAAASUVORK5CYII=
</rttac:InlineImage>
</FlowDocument>

主要是动态创建的Image也包含在了xaml里,我想有没有办法去掉 <rttac:InlineImage.Child>节点。先谢谢了。看了一个下午的MSDN,只找到这个
https://docs.microsoft.com/zh-cn/dotnet/framework/wpf/advanced/element-tree-and-serialization
但似乎没有我想要的内容,我希望InlineImage 能控制自己xaml的过程

自定义类的主要代码如下

[ContentProperty("Base64Source")]
public class InlineImage : BlockUIContainer, INameScope
{

//....
public string Base64Source
{
get { return (string)GetValue(Base64SourceProperty); }
set { SetValue(Base64SourceProperty, value); }
}
//...
private static void OnBase64SourceChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
var inlineImage = (InlineImage)sender;
var stream = new MemoryStream(Convert.FromBase64String(inlineImage.Base64Source));

var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();

var image = new Image
{
Source = bitmapImage,
Stretch = inlineImage.Stretch,
StretchDirection = inlineImage.StretchDirection,
};

if (!double.IsNaN(inlineImage.Width))
{
image.Width = inlineImage.Width;
}

if (!double.IsNaN(inlineImage.Height))
{
image.Height = inlineImage.Height;
}

inlineImage.Child = image;
}
}

...全文
406 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
assky124 2019-03-13
  • 打赏
  • 举报
回复
<rttac:InlineImage.Child> 这段不显示么? 试试 InlineImage 直接从ContentControl 派生,Child 不要,用Content属性取代 也可以试试用下面的特性修饰下你的Child属性。

    [ContentProperty("Content")]
    public class ContentControl : Control, IAddChild
.Net 现在开源了,不明白就看看源码
kevin2y 2019-03-13
  • 打赏
  • 举报
回复
引用 1 楼 龍月 的回复:
string xaml = XamlWriter.Save(img);
谢谢你的回帖,不过好象你没明白我的意思:)
龍月 2019-03-11
  • 打赏
  • 举报
回复
string xaml = XamlWriter.Save(img);

111,101

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧