0

我正在尝试从代码中的 ResourceDictionary 获取 DatatTemplate。问题是当我试图将它保存到字符串时,我得到所有绑定位置为空或空。

这是我的一段代码

    ResourceDictionary dictionary = new ResourceDictionary();
        dictionary.Source = new Uri("WpfApplication1;component/Dict.xaml", UriKind.RelativeOrAbsolute);
        DataTemplate template = (DataTemplate) dictionary["helloTextBox"];
        string save = XamlWriter.Save(template.LoadContent());

我会很高兴有任何见解。

谢谢

4

1 回答 1

0

事实证明,我需要在 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);
}

取自这里: 在后面的代码中设置模板绑定

于 2013-09-12T12:47:33.897 回答