2011-11-23 72 views
0

输出“米期待是这样的,设置模板代码结合背后

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

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

回答

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。非常感谢这个人

0

输出什么

如果您使用的是某种XamlWriter,您应该观察它的局限性,它们不保留绑定,如果您的意思是这是属性的值,那么您将无法绑定到类似的附属属性,你需要这个路径:(OwndingClass.AttachedProperty)(注意括号和拥有类前缀)

+0

路径将PropertyList.Min这是我的错误。 1)我使用Object obj = XamlReader.Load(*流指向预期的输出*)。 2)用obj玩一点。 3)string output = XamlWriter.Save(obj)在此输出字符串中,而不是绑定x:Null即将到来。 –

+0

@ vikram.ma:你可以忘记这一点,['XamlWriter'不写绑定](http://msdn.microsoft.com/en-us/library/ms754193.aspx#Extension_References_are_Dereferenced)。 –

+1

@ vikram.ma:我不知道任何这样的方法,为什么你需要这样做?通常情况下,如果你不能做的事情,这只是你不应该做的事情。 –