gpt4 book ai didi

c# - 如何在更改 SelectedIndex 时让 ComboBox.SelectedItem 绑定(bind)?

转载 作者:行者123 更新时间:2023-11-30 15:16:42 26 4
gpt4 key购买 nike

在我的应用程序中,当我的 combobox 的选择发生变化时,我需要更新某个图像。目前,我通过捕获 SelectedIndexChanged 事件并在那里更新图像来做到这一点。

我一直在尝试另一种方法来做到这一点,即使用 Binding 来简化我的代码,但它不起作用。

因为 ComboBox.SelectedItem 到特定属性的绑定(bind)仅在 ComboBox 失去焦点或另一个控件获得焦点时应用——不是在触发 SelectedIndexChanged 事件时或之前。

如何在 SelectedItemSelectedIndex 更改时立即应用绑定(bind)?

这是我的代码:

public partial class Form1 : Form
{

private readonly Person person;
public Form1()
{
InitializeComponent();

person = new Person()
{
Name = "joe",
Race = Race.Indian
};



textBox1.DataBindings.Clear();
textBox1.DataBindings.Add(nameof(textBox1.Text), person, nameof(person.Name));

comboBox1.DataSource = Enum.GetValues(typeof(Race));
comboBox1.DataBindings.Clear();
comboBox1.DataBindings.Add(nameof(comboBox1.SelectedItem), person, nameof(person.Race));
comboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged;

}

private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//when selected index is changed, the data is lagging behind the selected item.
//eg: SelectedItem is already Chinese, but person.Race is still Indian
MessageBox.Show($"data {person.Race}, selected item {comboBox1.SelectedItem}");
}

private int count = 0;

private void button1_Click(object sender, EventArgs e)
{
person.Race =(Race)(((int)person.Race + 1) % Enum.GetValues(typeof(Race)).Length);
person.Name = person.Name + $"{count++}";
}
}

public enum Race
{
Indian,
Chinese,
Causacian,
Arabian,
Jewish,
SouthINdian,
}
public class Person: INotifyPropertyChanged
{
private Race _race;
private string _name;
public string Name
{
get
{
return _name;

}
set
{
_name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
public Race Race
{
get
{
return _race;
}
set
{
_race = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs (nameof(Race)));

}
}

public event PropertyChangedEventHandler PropertyChanged;

}

最佳答案

要解决这个问题,可以绑定(bind)到SelectedValue属性:

comboBox1.DataSource = Enum.GetValues(typeof(Race)).Cast<Race>()
.Select(x => new { Value = x, Display = x.ToString() })
.ToList();
comboBox1.DisplayMember = "Display";
comboBox1.ValueMember = "Value";
comboBox1.DataBindings.Add(nameof(comboBox1.SelectedValue), person, nameof(person.Race),
true, DataSourceUpdateMode.OnPropertyChanged);

关于c# - 如何在更改 SelectedIndex 时让 ComboBox.SelectedItem 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48828395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com