2014-10-27 88 views
0

我希望得到一些關於我在代碼中缺少的指針。
我有一個文本框綁定到對象屬性是列表中的一個項目,如果我請求列表中的另一個項目,該值不會更新窗體上。Winforms雙向數據綁定:強制更新字段

要與下面的例子說明:
txtGain值openJSONRequestFileToolStripMenuItem_Click機能的研究後填充
一旦我選擇不同的cmbSignals組合框的東西,我希望因爲SelectedChannel更新以及將txtGain值變得更新,這反過來又更新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

很煩人的「功能」,不是嗎?

但是不用擔心,爲了解決這個問題,請在您更改req.SelectedChannel的值後在您的cmbSignals_SelectedValueChanged(sender, e)方法中添加一行代碼。

txtGain.BindingContext = new BindingContext();