我有一個ComboBox,其ItemsSource綁定到鏈接到ObservableCollection的新(非默認)ListCollectionView。 ComboBox SelectedItem屬性綁定到公共SelectedHat屬性。ComboBox的SelectedItem在實際值之前意外地設置爲空
步驟1:在ComboBox中選擇第二項。按照預期,SelectedHat現在是列表中的第二個帽子。 步驟2 :(點擊按鈕)將列表中的第二個點設置爲新的帽子。 SelectedHat首先設置爲null,然後設置爲新的Hat。
爲什麼在新帽子之前將SelectedHat設置爲null?
欲能夠vm.Collection [索引] =新帽()和
(1)如果ComboBox該索引選擇已,保持選定的去空白
(2)只設置SelectedHat代替一旦新的帽子,而不是空,然後將新帽
C#:
public partial class MainWindow : Window
{
private readonly ViewModel vm;
public MainWindow()
{
InitializeComponent();
vm = new ViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Hat item = new Hat { Name = "hat 2", Color = "Red"};
vm.Collection[1] = item;
}
}
public class ViewModel : BaseNotifyPropertyChanged
{
public ObservableCollection<Hat> Collection { get; set; }
public ListCollectionView View { get; set; }
private Hat selectedHat;
public Hat SelectedHat
{
get { return selectedHat; }
set
{
selectedHat = value;
Console.WriteLine(string.Format("SelectedHat set to [{0}]", value));
NotifyPropertyChanged("SelectedHat");
}
}
public ViewModel()
{
Collection = new ObservableCollection<Hat>()
{
new Hat { Name = "hat 1", Color = "Black" },
new Hat { Name = "hat 2", Color = "Black" },
new Hat { Name = "hat 3", Color = "Black" },
};
View = new ListCollectionView(Collection);
View.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
}
}
public class Hat
{
public string Name { get; set; }
public string Color { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Color);
}
}
public abstract class BaseNotifyPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
XAML:
<StackPanel>
<TextBlock Text="{Binding Path=SelectedHat, Mode=OneWay}" />
<ComboBox ItemsSource="{Binding Path=View}" SelectedItem="{Binding Path=SelectedHat, UpdateSourceTrigger=PropertyChanged}" />
<Button Content="click me" Click="Button_Click" />
</StackPanel>
查看我的回答。直接更新該項目並且沒有調用OnCollectionChanged。 – Paparazzi 2012-03-22 22:46:38
是的,我想說的是除了你提出的建議之外的其他工作:-) – Phil 2012-03-23 07:26:58