SL 4:将tabitem可见性绑定到复选框

时间:2011-05-16 21:24:06

标签: silverlight-4.0 binding


当我创建一个新的TabItem时,我会同时创建一个新的CheckBox 我想将TabItem的可见性绑定到CheckBox,但是在设置绑定时遇到了问题。

                CheckBox cb = new CheckBox();
                cb.Content = tabItemName;
                cb.Name = tabItemName;

                var visibilityBinding = new Binding("IsChecked");
                visibilityBinding.Mode = BindingMode.TwoWay;
                visibilityBinding.ElementName = cb.Name;  // this could just be a string literal 
                visibilityBinding.Converter = new VisibilityConverter();
                m.TabItem.SetBinding(TabItem.VisibilityProperty, visibilityBinding);

                cb.IsChecked = true;

在运行时我收到此错误:
        System.Windows.Data错误:BindingExpression路径错误:'Telerik.Windows.Controls.RadTabItem''Telerik.Windows.Controls.RadTabItem'(HashCode = 66442352)上找不到'IsChecked'属性。 BindingExpression:Path ='IsChecked'DataItem ='Telerik.Windows.Controls.RadTabItem'(HashCode = 66442352); target元素是'Telerik.Windows.Controls.RadTabItem'(Name ='Central ...'); target属性是'Visibility'(类型'System.Windows.Visibility')..

我做错了什么?我认为Binding ctor的参数是源对象(CheckBox)上的属性,它绑定到SetBinding()调用中指定的属性。

感谢您的任何建议......

更新
我加上了         visibilityBinding.Source = cb;

并在运行时收到此错误:
     使用Binding.Source

时无法设置Binding.RelativeSource

1 个答案:

答案 0 :(得分:1)

Binding.Source()是以编程方式绑定所必需的,并且与Binding.ElementName是唯一的 所以,这有效:

var visibilityBinding = new Binding("IsChecked");
visibilityBinding.Source = cb;
visibilityBinding.Mode = BindingMode.TwoWay;
// visibilityBinding.ElementName = cb.Name; 
visibilityBinding.Converter = new VisibilityConverter();
m.TabItem.SetBinding(RadTabItem.VisibilityProperty, visibilityBinding);

希望这有助于其他人......