在后台代码中设置模板绑定
本文关键字:绑定 设置 后台 代码 | 更新日期: 2023-09-27 18:15:33
我期望的输出是这样的,
<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>
我不知道怎么了,谁来帮帮我
找到答案了。使用下面的类
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。非常感谢这个家伙
什么输出?
如果你正在使用某种XamlWriter,你应该注意它的局限性,它们不保留绑定,如果你的意思是这是属性的值,也有意义,因为你不能绑定到附加的属性,你需要这个路径:(OwndingClass.AttachedProperty)
(注意括号和拥有的类前缀)