我有一个可编辑的组合框,我将name属性从对象列表绑定到(QBD.Name)。我无法弄清楚的是如何允许编辑这些名称 - 当我尝试编辑时,我不断收到对象引用错误。
我相信我需要实现INotifyPropertyChanged,但我不完全确定它是如何工作的。
这是绑定代码:
<ComboBox Name="cmbBxQBDNames" Text="Please Select a QBD" ItemsSource="{Binding Path=QBDs, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" DisplayMemberPath="QBD.Name" SelectedValuePath="QBD.Name" IsEditable="True" VerticalAlignment="Center" HorizontalAlignment="Stretch" Width="auto" MinWidth="25" Margin="45,0,0,0" Foreground="Black"></ComboBox>
这是我要绑定的对象:
Public Class QBDs
Private QBDsLocal As New ObservableCollection(Of QBD)
Public Property QBDs As ObservableCollection(Of QBD)
Get
Return QBDsLocal
End Get
Set(value As ObservableCollection(Of QBD))
QBDsLocal = value
End Set
End Property
End Class
Public Class QBD
Private NameLocal As String
Public Property Name As String
Get
Return NameLocal
End Get
Set(value As String)
NameLocal = value
End Set
End Property
End Class
另外,当我从组合框中选择一个对象时,如何在组合框中显示它的名字?目前,它仍然是空白。
答案 0 :(得分:0)
我认为你的问题在于DisplayMemberPath。
尝试使用DisplayMemberPath =“名称”
告诉我它是否失败。
答案 1 :(得分:0)
我无法理解为什么会失败,请参阅我编写的代码以测试您的问题。
<ComboBox ItemsSource="{Binding MyCollection}" DisplayMemberPath="FName" SelectedValuePath="SName" Height="40" IsEditable="True" />
//我的DataContext到这里
public class Model
{
private string sName;
public string SName
{
get { return sName; }
set { sName = value; }
}
private string fName;
public string FName
{
get { return fName; }
set { fName = value; }
}
}
public class ViewModel
{
private ObservableCollection<Model> myColl;
public ObservableCollection<Model> MyCollection
{
get { return myColl; }
set { myColl = value; }
}
public ViewModel()
{
MyCollection = new ObservableCollection<Model>();
MyCollection.Add(new Model { FName = "Tony", SName = "Strark" });
MyCollection.Add(new Model { FName = "Bruce", SName = "Wayne" });
MyCollection.Add(new Model { FName = "Miranda", SName = "Frost" });
}
}
//我将ViewModel设置为DataContext,
这对我来说很好用,请检查一次,请原谅我没有在VB中给出代码。
此致 库马尔