我希望能够对我的代码中缺少的内容有所了解 我有一个文本框绑定到一个对象属性,该属性是列表中的项目,如果我请求列表中的另一个项目,该值不会在表单上更新。
举例说明如下:
在openJSONRequestFileToolStripMenuItem_Click功能后填充txtGain值
一旦我在cmbSignals组合框中选择了不同的东西,我预计txtGain值会随着SelectedChannel的更新而更新,这反过来会更新selectedindex,但它不会发生。
基本上我想根据我在cmbSignals中选择的内容更新我的txtGain值。显然绑定是存在的,所以我可以修改文本框中的值,并在它绑定的属性中更新它。
我怀疑我必须以某种方式强制更新绑定但不知道如何做到这一点。任何帮助将不胜感激。
public partial class MainForm : Form
{
private MyData req;
public MainForm()
{
InitializeComponent();
cmbSignals.DisplayMember = "Name";
cmbSignals.ValueMember = "Value";
}
private void openJSONRequestFileToolStripMenuItem_Click(object sender, EventArgs e)
{
string text = File.ReadAllText("sample.json");
req = new MyData(JsonConvert.DeserializeObject<SerializedRequest>(text));
cmbSignals.DataSource = req.SignalNames;
cmbSignals.SelectedValue = req.SelectedChannel;
SetBindings();
}
private void SetBindings()
{
txtGain.DataBindings.Add(new Binding("Text", req, "Gain"));
}
private void cmbSignals_SelectedValueChanged(object sender, EventArgs e)
{
req.SelectedChannel = Convert.ToInt32(cmbSignals.SelectedValue);
}
}
public class MyData : INotifyPropertyChanged
{
private SerializedRequest Data = new SerializedRequest();
private int selectedIndex = 0;
public int SelectedChannel
{
get
{
return selectedIndex + 1;
}
set
{
this.selectedIndex = value - 1;
}
}
public string Gain
{
get
{
return Data.signals[selectedIndex].gain;
}
set
{
Data.signals[selectedIndex].gain = value;
OnPropertyChanged("Gain");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public List<SignalsCmbItem>SignalNames
{
get
{
List<SignalsCmbItem>channels = new List<SignalsCmbItem>();
for(int i = 0; i<Data.signals.Count;i++)
{
channels.Add(new SignalsCmbItem { Value = i + 1, Name = i+1 + " - " + Data.signals[i].label });
}
return channels;
}
}
}
答案 0 :(得分:0)
非常讨厌&#34;功能&#34;,不是吗?
但不用担心,为了解决这个问题,在更改cmbSignals_SelectedValueChanged(sender, e)
的值后,在req.SelectedChannel
方法中添加一行代码。
txtGain.BindingContext = new BindingContext();