Binding TreeView selection to ViewModel

瘦欲@ 提交于 2019-12-12 09:38:02

问题


So I have a TreeView that looks something like this:

<TreeView   Name="elementTreeView"
                        ItemsSource="{Binding Elements}" 
                        Width="Auto"
                        SelectedValuePath="Path" />

I also have a TextBlock defined as follows:

<TextBlock Text="{Binding ElementName=elementTreeView, Path=SelectedValue}" />

My ModelView is pretty basic and contains exactly what you would expect. What I'm looking for is a way to bind a property in my ViewModel to SelectedValue. Right now, the text block displays what I need. Is there any easy way to bind this property?


回答1:


So it turns out that this is the result of not following the MVVM pattern quite correctly. The solution was to just use one ViewModel object. Inside of the ViewModel (whose type is ElementViewModel) object, I had something like:

public ElementViewModel Element {
    get {
        return this;
    }
}

Then my TreeView declaration looked something like this:

<TreeView   Name="treeView" 
            ItemsSource="{Binding Elements}" 
            Width="Auto"
            SelectedValuePath="Element" />

After that, all I had to do was bind to Element in my other view.




回答2:


You can use a BindingMode of OneWayToSource to bind the TreeView's SelectedValue property to your ViewModel. Then bind the TextBlock's Text property using a OneWay binding to the same ViewModel property.




回答3:


You can bind the TreeView to a property on your ViewModel directly:

This will bind to the "SelectedItem" property in the VM.

<TreeView   Name="elementTreeView"
                    ItemsSource="{Binding Elements}" 
                    SelectedValue="{Binding SelectedItem, Mode=OneWayToSource}"
                    Width="Auto"
                    SelectedValuePath="Path" />


来源:https://stackoverflow.com/questions/2992780/binding-treeview-selection-to-viewmodel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!