How to get particular property from item selected in ListBox

只谈情不闲聊 提交于 2019-12-02 07:13:32

问题


I have the following:

<ListBox SelectedItem="{Binding SelectedItem}"
ItemsSource="{Binding items}" DisplayMemberPath="s"/>

<TextBlock Text="{Binding SelectedItem.s}"/>

This is definition of SelectedItem

public MemEntity SelectedItem {get; set;}

MemEntity is a class containing

public String s {get; get;}.

Basically, I want s of the selected item to be shown in the TextBlock (same property as shown in ListBox). This doesn't work, so what am I doing wrong?


回答1:


Try this,

<TextBlock ... Text="{Binding ElementName=items, Path=SelectedItem.s}" />

then add a name to your ListBox as,

  <ListBox x:Name="items" SelectedItem="{Binding SelectedItem}"
        ItemsSource="{Binding items}" DisplayMemberPath="s"/>



回答2:


There are multiple way to do this. One option has already been provided in another answer that focusing on achieving the desired functionality by binding to a view element. Here is another option.

The view is unaware that selected item has changed. look into using INotifyPropertyChanged

You can create a base ViewModel to encapsulate the repeated functionality

public abstract class ViewModelBase : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Have the view models inherit from this base class in order for the view to be aware of changes when binding.

public class ItemsViewModel : ViewModelBase {

    public ItemsViewModel() {
        items = new ObservableCollection<MemEntity>();
    }

    private MemEntity selectedItem;
    public MemEntity SelectedItem {
        get { return selectedItem; }
        set {
            if (selectedItem != value) {
                selectedItem = value;
                OnPropertyChanged(); //this will raise the property changed event.
            }
        }
    }

    public ObservableCollection<MemEntity> items { get; set; }
}

The view will now be aware when ever the SelectedItem property changes and will update the view accordingly.



来源:https://stackoverflow.com/questions/43963818/how-to-get-particular-property-from-item-selected-in-listbox

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