开发者

Binding Dependency Properties

So here I come creating a user control. It consists of a treeview dropping down from a combobox.

Actually, there is a button with a control (DropTree) dropping down from its contextmenu. So I have a control DropTree.

public partial class DropTree : UserControl
{
    public TreeView TreeView 
    { get{return treeView;} }

    public DropTree()
    { InitializeComponent(); }
}

to simplify it, I made the TreeView control public, then I have my main control which is called ComboTreeView.

Now I need to represent some treeview properties in it, so I define several dependency properties:

    public static DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(ComboTreeView), new FrameworkPropertyMetadata { Inherits = true, IsNotDataBindable = false, DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });

    public object SelectedItem
    {
        get { return GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

and in constructor it is:

public ComboTreeView()
{
 开发者_运维问答           InitializeComponent();
            TreeViewControl.SetBinding(TreeView.SelectedItemProperty, new Binding("SelectedItem") { Source = this, Mode = BindingMode.TwoWay });
}

and it all seems ok, until i run it. It crashes saying that SelectedItem cannot be binded to data. I don't understand?

The same goes for ItemsSource and SelectedValue... but only SelectedValuePath property defined this way goes fine.

Can anybody help? Or is there any other way to bind it correctly?

PS: by the way, I need to use DataBinding for ComboTreeView in my code later.


Try to set the Binding on SelectedValue instead of SelectedItem.


TreeView.SelectedItem is a readonly property. You can't set it, whether explicitly or through binding. In order to select a node in a TreeView, you must set the TreeViewItem.IsSelected property to true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜