![](/img/trans.png)
[英]Binding an ObservableCollection of Strings to a ListBox in WPF
[英]binding ListBox to ObservableCollection in WPF
我有一个名为Layer2Info的类
public class Layer2Info
{
public ObservableCollection<totalAvailablePorts> availableClientPorts = new ObservableCollection<totalAvailablePorts>();
}
totalAvailablePorts类为
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值更改为true ,我不知道从哪里开始。 有什么建议么?
首先, SelectedValuePath
不是您的想法。 MSDN说它 “获取或设置用于从SelectedItem
获取SelectedValue
的路径。” 因此,当用户选择一个项目时, clientPortsList
将采用其自己的SelectedItem
属性,并从clientPortsList.SelectedValue
返回该属性的值。 对于多选,这对您来说不是一个真正有用的概念,无论如何它与您在此处提出的问题无关。
对于每个totalAvailablePorts
实例,您要做的是totalAvailablePorts
实例的isSelected
属性绑定到拥有它的ListBoxItem
的IsSelected
属性。 您可以使用项目模板来做到这一点,但是样式要简单得多(如果您对重新创建或更改默认的ListBoxItem
视觉行为不感兴趣,则更好)。 这个答案已经在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)将在“范围内”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.