0

It seems that for a TreeView, the property SelectedItem cannot be used for binding. I am trying to understand how this can be consistent with the MSDN documentation.

On https://msdn.microsoft.com/en-us/library/system.windows.controls.treeview.selecteditem.aspx it says about the Treeview.SelectedItem property:

[BindableAttribute(true)]
public object SelectedItem { get; }

Then, this https://msdn.microsoft.com/en-us/library/system.componentmodel.bindableattribute.aspx says under "Remarks":

If a property has been marked with the BindableAttribute set to true, then a property change notification should be raised for that property. This means that if the Bindable property is Yes, then two-way data binding is supported. If Bindable is No, you can still bind to the property, but it should not be shown in the default set of properties to bind to, because it might or might not raise a property change notification.

I read it as "If your property has BindableAttribute set to true, you can bind to it; no matter which value is set to Bindable." Bindable is not listed in the [...] part for SelectedItem, which I assume means that Bindable is set to No.

So according to the documentation, binding to SelectedItem should work, right? Or am I misunderstanding something? If yes, what?

If I write

<TreeView SelectedItem="{Binding foo, Mode=OneWayToSource}" />

it says "The SelectedItem property does not have an accessible setter." (Original: "Die SelectedItem-Eigenschaft" verfügt über kein Setter-Objekt, auf das zugegriffen werden kann.)

But now I'm confused again - I told it to only use OneWayToSource binding, meaning that changes of SelectedItem reflect in foo, but not the other way around. So why does it even care about the setter? see OneWayToSource binding from readonly property in XAML , Pushing read-only GUI properties back into ViewModel

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Kjara
  • 2,504
  • 15
  • 42

1 Answers1

0

SelectedItem is only the reference to the item currently selected. You need to define the property of SelectedItemPath and DisplayMemberPath and then bind TreeView to collection via ItemsSource. Like this:

<TreeView ItemsSource="{Binding MyCollection}" DisplayMemberPath="Name" SelectedValuePath="Id" />

DisplayMemberPath - which property will be shown on GUI control (ie. Name of customer) SelectedValuePath - which property will be value of selected item (usually ID)

Edit: Just wanted to point to the "get" only property in SelectedItem

user3790083
  • 160
  • 2
  • 8