[wpf]请教如何控制自定义类的xaml序列化节点
我有一个自定义的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;
}
}