获取绑定列表框中所选项目的值



我想在listbox中显示的所选项目的doubleclick事件上获得string值。我使用的是mvvm体系结构。以下是代码:

<ListBox ItemsSource="{Binding RecentProjects}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock>
                         <Run Text="{Binding FileName}"/>
                         <Run Text="{Binding CreationTime}"/>
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseDoubleClick">
                <i:InvokeCommandAction Command="{Binding SelectedCommand}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ListBox>

我的ViewModel中的代码如下:

private ObservableCollection<FileItem> _recentProjects = new ObservableCollection<FileItem>();
public ObservableCollection<FileItem> RecentProjects
    {
        get { return _recentProjects; }
        set { _recentProjects = value; }
    }
public RelayCommand SelectedCommand { get; private set; }
private void Selected()
    {
        //string fileName = RecentProjects.SelectedItem ===> Need stringvalue of filename
    }

在FileItem模型中,我有一个FileName和一个CreationTime属性。我想获得RecentProjectsObservablecollection中selecteditem的FileName的字符串值。我该怎么做?

您应该将属性定义为ListBox.SelectedItem:

您的视图模型:

    FileItem _myItem;
    public FileItem MyItem
    {
        get
        {
            return _myItem;
        }
        set
        {
            _myItem = value;
            OnPropertyChanged("MyItem");
        }
    }
    private void Selected()
    {
        string fileName = MyItem.FileName;
    }

您的Xaml:

<ListBox ItemsSource="{Binding RecentProjects}" SelectedItem="{Binding MyItem}">
        <ListBox.ItemTemplate> ...

相关内容

  • 没有找到相关文章

最新更新