How to get particular property from item selected in ListBox

会有一股神秘感。 提交于 2019-12-02 04:59:37

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"/>

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.

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