事实证明,我需要在 TypeConverter 中为 BindingExpression 注册一个绑定转换器,以便序列化在绑定上工作,因为默认情况下它们没有序列化。
需要将此类添加为 ExpressionConverter
public class BindingConverter : ExpressionConverter
{
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, Type destinationType)
{
return true;
}
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(MarkupExtension))
{
BindingExpression bindingExpression = value as BindingExpression;
if (bindingExpression == null)
{
throw new FormatException("Expected binding, but didn't get one");
}
return bindingExpression.ParentBinding;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
然后使用此方法注册我执行 XamlWriter.Save 部分的位置
private void Register()
{
Attribute[] attr = new Attribute[1];
TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(BindingConverter));
attr[0] = vConv;
TypeDescriptor.AddAttributes(typeof(BindingExpression), attr);
}
取自这里:
在后面的代码中设置模板绑定