gpt4 book ai didi

c# - 控制不立即使用 INotifyPropertyChanged 更新绑定(bind)属性

转载 作者:IT王子 更新时间:2023-10-29 04:48:51 26 4
gpt4 key购买 nike

我的控件在失去焦点之前不会更新其绑定(bind)对象的相应属性。有类似的问题,接受的答案引用 DataSourceUpdateMode.OnPropertyChange 被声明,我这样做,但行为仍然存在。这是一个示例实现。我会尽量做到全面而简洁。 MyConfig 类是通过我称为 Configuration 的 Singleton 类中的属性访问的。

[Serializable]
public class MyConfig : INotifyPropertyChanged
{
public enum MyEnum
{
Foo,
Bar
}

public MyConfig()
{
MyProperty = MyEnum.Foo;
}

private MyEnum _MyProperty;
public MyEnum MyProperty
{
get { return _MyProperty; }
set { if (value != _MyProperty) { _MyProperty = value; OnPropertyChanged("MyProperty"); } }
}

[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentNullException(propertyName);
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

public partial class ConfigForm : Form
{
public ConfigForm()
{
InitializeComponent();
MyComboBox.Items.AddRange(Enum.GetNames(typeof(MyConfig.MyEnum)));
}

private void ConfigForm_Load(object sender, EventArgs e)
{
MyComboBox.DataSource = Enum.GetValues(typeof(MyConfig.MyEnum));
MyComboBox.DataBindings.Add("SelectedItem", Configuration.Instance.MyConfig, "MyProperty", false, DataSourceUpdateMode.OnPropertyChanged);
}
}

鉴于以下简要实现,我不确定我可能会忽略哪些内容以确保立即更改属性。在本例中,我可以更改 ComboBox 中的 FooBar,但除非我从 ComboBox 中移除焦点,否则什么都不会改变。有人有什么想法吗?

最佳答案

WinForms ComboBoxOnPropertyChanged 有关。下面是我用来使 OnPropertyChanged 以我期望的方式为 SelectedItem 属性工作的旧项目的一些代码。这适用于我的特定实例,但有时我通常很难让这种情况发挥作用。祝你好运!

/// <summary>
/// A modification of the standard <see cref="ComboBox"/> in which a data binding
/// on the SelectedItem property with the update mode set to DataSourceUpdateMode.OnPropertyChanged
/// actually updates when a selection is made in the combobox.
/// </summary>
public class BindableComboBox : ComboBox
{
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.ComboBox.SelectionChangeCommitted"/> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
protected override void OnSelectionChangeCommitted(EventArgs e)
{
base.OnSelectionChangeCommitted(e);

var bindings = this.DataBindings
.Cast<Binding>()
.Where(x =>
x.PropertyName == "SelectedItem" &&
x.DataSourceUpdateMode == DataSourceUpdateMode.OnPropertyChanged);
foreach (var binding in bindings)
{
// Force the binding to update from the new SelectedItem
binding.WriteValue();

// Force the Textbox to update from the binding
binding.ReadValue();
}
}
}

关于c# - 控制不立即使用 INotifyPropertyChanged 更新绑定(bind)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8392019/

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