在后面的代码中设置模板绑定

时间:2011-11-23 09:32:51

标签: c# wpf xaml data-binding

预期的输出是这样的,

<Canvas Width="800" Height="600">
   <Ellipse Stroke="#FF000000" StrokeThickness="2" Width="284" Height="288" 
            ToolTip="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Min}" 
            Canvas.Left="312" Canvas.Top="122" />
</Canvas>

使用此代码,

//This will ultimately hold object of type UIElement, which is Ellipse in this case.
private DependencyObject selectedObject; 

public void AddBinding(DependencyProperty dependencyProperty, DependencyProperty ipartProperty)
{
    Binding binding = new Binding(ipartProperty.Name); //Here Name is Min, an attached property
    binding.RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent);
    BindingOperations.SetBinding(selectedObject, dependencyProperty, binding);
}

但实际输出是

<Canvas Width="800" Height="600">
   <Ellipse Stroke="#FF000000" StrokeThickness="2" Width="284" Height="288" 
            ToolTip="{x:Null}" Canvas.Left="312" Canvas.Top="122"/>
</Canvas>

我不知道什么是错的,有人可以请帮忙

2 个答案:

答案 0 :(得分:1)

找到答案。使用以下课程

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(obj)

将此方法添加到类中
private void Register()
    {
        Attribute[] attr = new Attribute[1];
        TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(BindingConverter));
        attr[0] = vConv;
        TypeDescriptor.AddAttributes(typeof(BindingExpression), attr);
    }

得到了我想要的答案! 归功于Alex Dov http://www.codeproject.com/script/Membership/View.aspx?mid=106815。非常感谢这个人

答案 1 :(得分:0)

输出什么

如果你正在使用某种XamlWriter,你应该注意它的局限性,它们不保留绑定,如果你的意思是这个属性的值也是有意义的,因为你不能绑定到这样的附加属性,你需要此路径:(OwndingClass.AttachedProperty) (注意括号和拥有类前缀)