简体   繁体   English

在MVVM中获取列表框SelectedValue

[英]Get Listbox SelectedValue in MVVM

I have a MainWindow that contains A listbox, and a ContentControl, each time you select something from the Listbox, the ContentControl will display something else. 我有一个MainWindow,其中包含一个列表框和一个ContentControl,每次您从列表框中选择内容时,ContentControl都会显示其他内容。

   <ContentControl Content="{Binding ElementName=SomeList, Path=SelectedItem.Content}" />

  <ListBox  x:Name="SomeList" Margin="0 16 0 16" SelectedIndex="0"  SelectedValue="{Binding X}"            
                         ItemsSource="{Binding DemoItems}">

ViewModel: 视图模型:

 private string _X;
    public string X

    {
        get { return _X; }
        set
        {
            _X = value;
            NotifyOfPropertyChange("X");
        }
    }

Trying to display X will result in the same thing: 尝试显示X将导致相同的结果:

namespace.DemoItem namespace.DemoItem

DemoItem.cs: DemoItem.cs:

 public class DemoItem : INotifyPropertyChanged
{
    private object _icon;
    private string _name;
    private object _content;
    private Thickness _marginRequirement;

    public DemoItem(object icon, string name, object content, Thickness margin,  IEnumerable<DocumentationLink> documentation)
    {
        _icon = icon;
        _name = name;
        Content = content;
        _marginRequirement = margin;

        Documentation = documentation;
    }
} 

So how is it possible to only get the name? 那么怎么可能只获得名字呢?

Data binding only works with public properties. 数据绑定仅适用于公共属性。 So add a Name property 因此添加一个Name属性

public class DemoItem : INotifyPropertyChanged
{
    ...
    public string Name { get { return _name; } }
}

Assuming that yous intention is to selected a DemoItem by its Name , you should also set the ListBox's SelectedValuePath in conjunction with SelectedValue : 假设你要跟目的是要选择通过其在DemoItem Name ,你也应该设定ListBox的SelectedValuePath会同SelectedValue

<ListBox ItemsSource="{Binding DemoItems}"
         SelectedValuePath="Name"
         SelectedValue="{Binding X}" />

Then simply display the selected item's Name like this: 然后只需显示所选项目的名称,如下所示:

<TextBlock Text="{Binding X}" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM