将ListBox绑定到WPF中的ObservableCollection

时间:2013-12-12 17:50:44

标签: c# wpf binding listbox observablecollection

我有一个名为Layer2Info的类

    public class Layer2Info
{
    public ObservableCollection<totalAvailablePorts> availableClientPorts = new ObservableCollection<totalAvailablePorts>();
}

totalAvailablePorts Class是

    public class totalAvailablePorts : INotifyPropertyChanged
{
    public int _portID;
    public Boolean _isSelected;

    public int portID
    {
        get { return _portID; }
        set { _portID = value; NotifyPropertyChanged("portID"); }
    }
    public Boolean isSelected
    {
        get { return _isSelected; }
        set { _isSelected = value; NotifyPropertyChanged("isSelected"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public override string ToString()
    {
        return string.Format("{0}", portID);
    }
}

在availableClientPorts中创建数据是:

            for (int i = 1; i <= 3; i++)
        {
            totalAvailablePorts newPort = new totalAvailablePorts();
            newPort.portID = i;
            newPort.isSelected = false;
            layer2InfoConfig.availableClientPorts.Add(newPort);              
        }

现在,在我的MainWindow中,我将ListBox绑定到Layer2Info.availableClientPorts,如下所示:

clientPortsList.ItemsSource = layer2InfoConfig.availableClientPorts;

最后是我的xaml:

<ListBox x:Name="clientPortsList" 
         SelectionMode="Extended" 
         DisplayMemberPath="{Binding Path=portID}" 
         SelectedValuePath="{Binding Path=isSelected}" 
         Height="50"/>

现在,我能够看到ListBox中的所有端口(1-3),但我想要做的是在ListBox中选择的每一行,我想要在availableClientPorts中的isSelected值变为真,我不知道从哪里开始。 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

首先,SelectedValuePath不是您的想法。 MSDN says它“获取或设置用于从SelectedValue获取SelectedItem的路径。”因此,当用户选择一个项目时,clientPortsList将获取其自己SelectedItem的该属性,并从clientPortsList.SelectedValue返回该属性的值。对于多选,这对你来说不是一个真正有用的概念,无论如何它与你在这里提出的问题无关。

您要做的是,对于每个totalAvailablePorts实例,将该实例的isSelected属性绑定到拥有它的IsSelected属性。ListBoxItem。您可以使用项目模板执行此操作,但Style更简单(如果您对重新创建或更改默认的ListBoxItem视觉行为不感兴趣,则更好)。答案是already on StackOverflow

<ListBox ItemsSource="..."
    x:Name="clientPortsList" 
    SelectionMode="Extended" 
    DisplayMemberPath="{Binding Path=portID}" >
  <ListBox.ItemContainerStyle>
   <Style TargetType="{x:Type ListBoxItem}">
     <!-- binding totalAvailablePorts.isSelected to ListBoxItem.IsSelected -->
     <Setter Property="IsSelected" Value="{Binding isSelected}"/>
   </Style>
  </ListBox.ItemContainerStyle>
 </ListBox>

对于ListBoxItem个实例,他们的DataContext将是他们各自的totalAvailablePorts个实例,因此isSelected(小写I)将在“范围内”。