【发布时间】:2015-12-15 10:10:34
【问题描述】:
我有一个ComboBox,其SelectedItem 和ItemsSource 是数据绑定到视图模型的。无论何时选择"Blue",SETTER反而设置了值"Green"并触发PropertyChanged事件。
我希望ComboBox 在这种情况下显示"Green",而不是显示的值仍然是"Blue"。
我用CheckBox(绑定到IsChecked,将值恢复为false,只要它设置为true并触发PropertyChanged),它就可以正常工作了。
MainWindow.xaml:
<Window x:Class="WpfTestApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="80" Width="100">
<Grid>
<ComboBox x:Name="ComboBox" SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding Values}" />
</Grid>
</Window>
MainWindow.xaml.cs:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
namespace WpfTestApplication
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ComboBox.DataContext = new ViewModel();
}
}
public class ViewModel : INotifyPropertyChanged
{
public List<string> Values { get; set; } = new List<string>
{
"Green", "Red", "Blue"
};
public string SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
if (selectedItem == "Blue")
selectedItem = "Green";
SelectedItemChanged();
}
}
private string selectedItem = "Red";
public event PropertyChangedEventHandler PropertyChanged;
public void SelectedItemChanged() =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItem)));
}
}
【问题讨论】:
-
检查 Combobox IsSynchronizedWithCurrentItem 属性是否设置为“True”。
-
呃。多年后,这个仍然是一个令人头疼的问题:) 两个答案都有效,但有延迟的那个看起来更糟,因为人们可以看到延迟开始了。
标签: c# wpf xaml data-binding combobox