How to get particular property from item selected

2020-04-30 07:29发布

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?

标签: c# wpf listbox
2条回答
迷人小祖宗
2楼-- · 2020-04-30 07:42

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"/>
查看更多
倾城 Initia
3楼-- · 2020-04-30 07:49

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.

查看更多
登录 后发表回答