TreeView控件绑定挑选视图模型 [英] Binding TreeView selection to ViewModel

查看:154
本文介绍了TreeView控件绑定挑选视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个TreeView,看起来是这样的:

So I have a TreeView that looks something like this:

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

我也有定义一个TextBlock如下:

I also have a TextBlock defined as follows:

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

我的模型视图是pretty基础,准确地包含了你所期望的。我正在寻找的是绑定在我的ViewModel到的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?

推荐答案

因此​​,原来,这是不太正确继MVVM模式的结果。解决的办法是只使用一个视图模型对象。里面的视图模型(类型为ElementViewModel)的对象,我有这样的事情:

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;
    }
}

然后我的TreeView控件声明看起来是这样的:

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.

这篇关于TreeView控件绑定挑选视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆