首页 新闻 会员 周边

windows phone 中自定义控件中动态绑定

0
悬赏园豆:50 [待解决问题]

这个问题折磨我一天了,求园友帮忙啊。

在windows phone中自定义一个控件,继承自Control,类已经完成了。我将在Themes/Generic.xaml中的默认模板的一个SolidColorBrush生成这个控件的部件,在重写的OnApplyTemplate中进行动态绑定,和我自己定义的一个依赖属性绑定在一起。可是怎么也不成功。但是在xaml的默认模板中绑定成<SolidColorBrush x:Name="PART_PreviewBrush" Color="{Binding Path=Color,RelativeSource={RelativeSource TemplatedParent}}"/>,就能绑定成功。我在C#硬编码中的绑定是这样的:

SolidColorBrush brush = GetTemplateChild("PART_PreviewBrush") as SolidColorBrush;
if (brush != null)
{
Binding binding = new Binding("Color");
binding.Source = brush;
binding.Mode = BindingMode.TwoWay;
this.SetBinding(ColorProperty, binding);
}

求解,谢谢!

Monte的主页 Monte | 初学一级 | 园豆:154
提问于:2014-10-30 16:11
< >
分享
所有回答(1)
0

问题解决了。因为SolidColorBrush之类的类不是继承自FrameworkElement,若是想实现它们的依赖属性的绑定可以使用BindingOperations.SetBinding函数进行绑定。我上面的方法是看的一本WPF的书上介绍的,但是区别是书上说的BindingMode是OneWayToSource,而Silverlight中没有,我改成TwoWay,可是也是行不通。

改好的代码如下:

SolidColorBrush brush = GetTemplateChild("PART_PreviewBrush") as SolidColorBrush;
if (brush != null)
{
  Binding binding = new Binding("Color");
  binding.Source = this;
  binding.Mode = BindingMode.TwoWay;
  BindingOperations.SetBinding(brush, SolidColorBrush.ColorProperty, binding);
}

Monte | 园豆:154 (初学一级) | 2014-10-31 09:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册