【问题标题】:Change bound Property when programmatically changing SelectedIndex以编程方式更改 SelectedIndex 时更改绑定属性
【发布时间】:2012-03-10 19:02:47
【问题描述】:

我已经设置了一个简单的表单。 ListBox 从显示 Name 属性并提供 Value 属性的“业务对象”中的列表中获取值。

此外,ListBox 的 SelectedItem 属性绑定到同一业务对象中的属性。

使用 UI 从列表中正确选择值会更改对象属性(单击按钮时检查)并且正确的值可用。到目前为止一切顺利。

但是,如果在代码中更改了 ListBox 的 SelectedIndex 属性,则 UI 会按预期正确更改,但业务属性不会更改 - 它似乎错过了更改事件。对于构造函数和按钮事件处理程序中的设置都是如此(参见代码)。 我错过了什么或者我做错了什么。 (我只包含了我编写的代码 - 不是 VS 向导生成的东西)

class Frequency
{
    public String Name { get; set; }
    public Int16 Value { get; set; }

    public Frequency(String name, Int16 value)
    {
        Name = name;
        Value = value;
    }
}

class FrequencyList : System.ComponentModel.BindingList<Frequency>
{
}

class Model
{
    public static FrequencyList FrequencyValues = new FrequencyList() 
    {
        new Frequency("Slowest", 100),
        new Frequency("Slow", 150),
        new Frequency("Medium", 1000),
        new Frequency("Fast", 5500),
        new Frequency("Fastest", 10000)
    };

    public Frequency StartFrequency { get; set; }

    public void DoStuff()
    {
        if (StartFrequency == null)
            return;

        Int16 freq = StartFrequency.Value;
    }
}

    public partial class Form1 : Form
{
    private Model myModel = new Model();

    public Form1()
    {
        InitializeComponent();

        // Bind the list to a copy of the static model data
        this.listBox1.DataSource = Model.FrequencyValues;
        // Bind the control to the model value
        this.listBox1.DataBindings.Add("SelectedItem", myModel, "StartFrequency");
        // Select the start value
        this.listBox1.SelectedIndex = 3;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Int16 f = (Int16)listBox1.SelectedValue;

        this.myModel.DoStuff();
        int new_index = listBox1.SelectedIndex + 1;
        if (new_index >= listBox1.Items.Count)
            new_index = 0;
        listBox1.SelectedIndex = new_index;
    }
}

【问题讨论】:

    标签: c# .net winforms visual-studio-2010


    【解决方案1】:

    你不想要Click 事件,你想要SelectedIndexChanged 事件。无论是用户还是程序发起更改,这都会触发。

    【讨论】:

    • 对不起,糟糕的驾驶。点击事件仅用于测试。我可以使用 SelectedIndexChanged 事件强制业务对象更新——但这不是我想要做的。如果 StartFrequency 属性正在通过 UI 更改进行更新,为什么在程序中设置 SelectedIndex 时它没有更新?
    • @Gray-M 不,我的意思是你需要在listBox1_SelectedIndexChanged 中有freq.value = Convert.ToInt16(listBox1[listBox1.SelectedIndex].Text) 并确保你已经将它链接到控件...或者通过在“属性”工具栏中自动生成它或通过在表单初始化中的某处添加this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged); 手动进行。然后你可以通过listBox1.SelectedIndex=3 或其他任何东西自动触发它。
    • 好的,这确实有效,但是不需要从表单到对象的数据绑定。事件处理程序完成所有工作。我试图让绑定来完成这一切。
    猜你喜欢
    • 2017-02-27
    • 2013-09-11
    • 2021-09-03
    • 2016-05-22
    • 1970-01-01
    • 2019-09-20
    • 2011-07-30
    • 2010-12-05
    • 1970-01-01
    相关资源
    最近更新 更多