這是我的問題...我有一個服務器列表,每個服務器都有一個ID和ServerName。我希望能夠從ComboBox中選擇一個服務器並對其進行編輯,然後讓它的ID可用於稍後通過SQL進行更新。假設這是數據:(ID = 1,Name =「Server1」),(ID = 2,Name =「Server2」),(ID = 3,Name =「Server3」)。如果我從ComboBox中選擇Server3,我想將其編輯爲「Server4」,然後用SQL查詢上傳(我知道如何完成這部分)。我正在使用MVVM,所以所有的值都是我的ViewModel的屬性。MVVM可編輯組合框綁定
當前,當在ComboBox中修改文本字段時,SelectedServer立即變爲空,大概是因爲它不再是它識別的值。我可以使用一些指導來了解如何讓它做我想做的事情。
<ComboBox Grid.Column="1" x:Name="serverNameUpdateBox" HorizontalAlignment="Stretch" Height="23" VerticalAlignment="Center" IsEditable="True"
ItemsSource="{Binding Path=DataContext.SelectedProjectServers, ElementName=main}"
DisplayMemberPath="ServerName"
SelectedValue="{Binding SelectedServer}"
SelectedValuePath="ServerName"
Text="{Binding SelectedServer.ServerName, UpdateSourceTrigger=LostFocus}"
/>
而且視圖模型相關代碼:
namespace ViewModel
{
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
SelectedProjectServers = new List<Server>();
SelectedServer = new Server();
private Server _selectedServer;
public Server SelectedServer
{
get { return _selectedServer; }
set
{
if (value == null) { ModifiedServer = _selectedServer; }
_selectedServer = value;
RaisePropertyChanged("SelectedServer");
}
}
private List<Server> _selectedProjectServers;
public List<Server> SelectedProjectServers
{
get { return _selectedProjectServers; }
set
{
_selectedProjectServers = value;
RaisePropertyChanged();
}
}
}
}
}
和型號相關代碼:
namespace Model
{
public class Server : INotifyPropertyChanged
{
private string _serverName;
public string ServerName
{
get { return _serverName; }
set
{
_serverName = value;
RaisePropertyChanged();
}
}
private int _serverID;
public int ServerID
{
get { return _serverID; }
set
{
_serverID = value;
RaisePropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string caller = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(caller));
}
}
}