我在WPF中的數據綁定中苦苦尋找過我仍然看不到我缺少的模型以更新所選項目名單。 我有2個實體插槽和SlotTypeWPF twoway在WPF中建模的數據綁定列表框無法獲取選定的值
public class Slot : BindableObject, INotifyPropertyChanged
{
private int slotID;
public int SlotID
{
get { return slotID; }
set
{
if (slotID != value)
{
slotID = value;
RaisePropertyChanged("SlotID");
}
}
}
private string user;
public string SlotUser
{
get { return user; }
set
{
if (user != value)
{
user = value;
RaisePropertyChanged("SlotUser");
}
}
}
private int slotUserID;
public int SlotUserID
{
get { return slotUserID; }
set
{
if (slotUserID != value)
{
slotUserID = value;
RaisePropertyChanged("SlotUserID");
}
}
}
private int slotType;
public int SlotType
{
get { return slotType; }
set
{
if (slotType != value)
{
slotType = value;
RaisePropertyChanged("SlotType");
}
}
}
private DateTime slotStartDateTime;
public DateTime SlotStartDateTime
{
get { return slotStartDateTime; }
set
{
if (slotStartDateTime != value)
{
slotStartDateTime = value;
RaisePropertyChanged("SlotStartDateTime");
}
}
}
public class SlotType : BindableObject, INotifyPropertyChanged
{
private int slotTypeID;
public int SlotTypeID
{
get { return slotTypeID; }
set
{
if (slotTypeID != value)
{
slotTypeID = value;
RaisePropertyChanged("SlotTypeID");
}
}
}
private string slotTypeDesc;
public string SlotTypeDesc
{
get { return slotTypeDesc; }
set
{
if (slotTypeDesc != value)
{
slotTypeDesc = value;
RaisePropertyChanged("SlotTypeDesc");
}
}
}
public override string ToString()
{
return SlotTypeDesc;
}
}
我然後創建一個包含一個類,並設置我的窗口背景是這個類。
public class SlotWithTypes
{
public ObservableCollection<SlotType> slotTypes { get; set; }
public Slot slot { get; set; }
}
從我的主窗口,我測試,如果需要在新窗口打開顯示SlotTypes列表供用戶選擇哪種類型有關創建插槽。
Slot slot = new Slot();
slot.SlotStartDateTime = item.SlotStartDateTime;
if (item.SlotType == 0)
{
SlotWithTypes swtype = new SlotWithTypes();
swtype.slotTypes = slotTypes;
swtype.slot = slot;
SelectSlotType stype = new SelectSlotType();
stype.DataContext = swtype;
stype.ShowDialog();
}
最後,在我的XAML我有我的列表框
<Grid>
<ListBox Name="lstSlotTypes"
HorizontalAlignment="Left"
Height="200"
Margin="0,10,0,0"
VerticalAlignment="Top"
Width="194"
ItemsSource="{Binding slotTypes}"
SelectedItem="{Binding Path=slot.Type, Mode=TwoWay}"
SelectedValue="{Binding slotTypes.SlotTypeID, Mode=TwoWay}"
SelectedValuePath="{Binding slot.Type, Mode=TwoWay}"
DisplayMemberPath="{Binding slotTypes.SlotTypeDesc}"
SelectionChanged="lstSlotTypes_SelectionChanged">
</ListBox>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="10,246,0,0"
TextWrapping="Wrap"
Text="{Binding slot.SlotStartDateTime, Mode=TwoWay}"
VerticalAlignment="Top"
Width="74"/>
</Grid>
爲了測試我把綁定到哪個工作和更新回到我的模型slotstartdatetime一個文本框。我已經嘗試了列表框上的各種綁定格式,並且可以獲取我的SlotTypes列表來顯示put無法使用所選值更新Slot實體。
我意識到這已經成爲一個長期的問題,但請如果有人能看到我做錯了什麼?
這是什麼邏輯? 1.我打開窗戶時有一系列物品? 2.列表框中是否有任何項目? – Ilan
您確定,在SelectedValuePath和DisplayMemberPath中您需要綁定? :)必須有一些屬性名稱。 – Spawn