2011-11-23 29 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:我不知道任何這樣的方法,爲什麼你需要這樣做?通常情況下,如果你不能做的事情,這只是你不應該做的事情。 –