我有一個ComboBox綁定到一個CollectionViewSource,我希望默認情況下選定的索引應該是-1(因爲什麼都不應該被選中)我已經設置SelectedIndex =「 -1「 並且第一項仍處於選中狀態。爲什麼?組合框選定的索引-1綁定到集合查看源
我查看XAML:
<Window.Resources>
<CollectionViewSource x:Key="States" Source="{Binding States}"/>
<CollectionViewSource x:Key="Cities" Source="{Binding Source={StaticResource States}, Path=Cities}"/>
</Window.Resources>
<ComboBox SelectedValue="{Binding Person.State}" Width="150" SelectedValuePath="StateInitial" DisplayMemberPath="StateName" ItemsSource="{Binding Source={StaticResource States}}"/>
<ComboBox SelectedValue="{Binding Person.City}" Width="150" SelectedValuePath="CityId" DisplayMemberPath="CityName" ItemsSource="{Binding Source={StaticResource Cities}}"/>
型號C#
public class State
{
public State(string stateInitial, string stateName, ICollection<City> cities)
{
StateInitial = stateInitial;
StateName = stateName;
Cities = cities;
}
public string StateInitial { get; set; }
public string StateName { get; set; }
public virtual ICollection<City> Cities { get; set; }
}
public class City
{
public int CityId { get; set; }
public string CityName {get;set;}
}
public class Person : INotifyPropertyChanged
{
#region Fields
private string state;
private int city;
#endregion
public string State
{
get
{
return state;
}
set
{
state = value;
OnPropertyChanged("State");
}
}
public int CityId
{
get
{
return city;
}
set
{
city = value;
OnPropertyChanged("City");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
視圖模型C#
public class MainWindowViewModel
{
public Person NewPerson { get; set; }
public List<State> States { get; private set; }
public MainWindowViewModel()
{
States = GetStates();
NewPerson = new Person();
}
public List<State> GetStates()
{
var stateList = new List<State>();
var TaxesCities = new List<City>();
TaxesCities.Add(new City(){ CityId = 1, CityName = "Dalles"});
TaxesCities.Add(new City(){ CityId = 2, CityName = "Houstin"});
stateList.Add(new State("TX", "Taxes" , TaxesCities));
var NYCities = new List<City>();
NYCities.Add(new City() { CityId = 3, CityName = "New York" });
NYCities.Add(new City() { CityId = 4, CityName = "Brooklyn" });
stateList.Add(new State("NY", "New York", NYCities));
return stateList;
}
}
謝謝你的迴應,但選項1和3似乎沒有工作選項2的作品,但我認爲它有點凌亂 – 2014-10-30 18:11:44
奇怪,我測試了這兩種方法,並在.NET 4.5中,至少他們工作得很好。我猜別的東西是干擾綁定,發佈一個最小例子的任何機會? – 2014-10-30 21:57:31
感謝您的回覆我編輯了問題添加了更多的代碼在我的情況下,我有一個動態數據列表,所以添加一個項目應該顯示「請選擇一個」不是一個選項 – 2014-11-04 21:44:41