在代码背后设置模板绑定 [英] Setting template binding in code behind

查看:112
本文介绍了在代码背后设置模板绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输出结果是这样的,

<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>

我不知道有什么问题,有人可以帮助

I don't know whats wrong, can someone please help

推荐答案

找到答案。使用以下类

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将该方法添加到类中。保存(obj)

Add this method to the class from you call 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 。非常感谢这位家伙

And got the answer i wanted!!! The credit goes to Alex Dov http://www.codeproject.com/script/Membership/View.aspx?mid=106815 . Thanks a lot to this guy

这篇关于在代码背后设置模板绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆