我有一个 ComboBox,它的 ItemsSource 绑定到一个新的(不是默认的)ListCollectionView,它链接到一个 ObservableCollection。ComboBox SelectedItem 属性绑定到公共 SelectedHat 属性。
第 1 步:选择 ComboBox 中的第二项。正如预期的那样,SelectedHat 现在是列表中的第二个帽子。第 2 步:(单击按钮)将列表中的第二个位置设置为新帽子。SelectedHat 首先设置为 null,然后设置为新 Hat。
为什么 SelectedHat 在新 Hat 之前设置为 null?
我希望能够 vm.Collection[index] = new Hat() 和
(1) 如果 ComboBox 选择了该索引,则保持选中而不是空白
(2) 只将 SelectedHat 设置为新 Hat 一次,而不是null 然后是新帽子
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>