INotifyPropertyChanged在使用反射动态绑定时不起作用

本文关键字:绑定 定时 不起作用 动态 反射 INotifyPropertyChanged | 更新日期: 2023-09-27 18:04:55

我遇到了INotifyPropertyChanged事件在代码中绑定所选项目时不工作的问题。一切加载良好,但INotifyPropertyChanged事件永远不会触发,当我改变我的选择。帮助吗?

public enum Foods
{
    Burger,
    Hotdog
}
public enum Drinks
{
    Pop,
    Coffee
}
// Enum collection class
public class FoodEnumerationCollection: INotifyPropertyChanged
{
    /// <summary>
    /// Declare the event
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;
    private Foods food;
    private Drinks drink;
    public Foods Food 
    {
        get
        {
            return this.food;
        }
        set
        {
            this.food= value;
            OnPropertyChanged("Food");
        }
    }
    public Drinks Drink
    {
        get
        {
            return this.drink;
        }
        set
        {
            this.drink= value;
            OnPropertyChanged("Drink");
        }
    }
    #region Protected Methods
    /// <summary>
    /// Create the OnPropertyChanged method to raise the event for UI
    /// </summary>
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}

在我的主类中,我有这样的内容:

// instantiate food enumeration class
FoodEnumerationCollection foodEnumerationCollection = new FoodEnumerationCollection();
// Loop through all properties
foreach (PropertyInfo propertyInfo in this.foodEnumerationCollection.GetType().GetProperties())
{
            if (propertyInfo.CanWrite)
            {
                ComboBox comboBox = new ComboBox();
                comboBox.Name = propertyInfo.Name;
                comboBox.Margin = new Thickness(5, 5, 5, 5);
                comboBox.Width = 100;
                comboBox.Height = 25;
                // DataSource
                comboBox.ItemsSource = Enum.GetValues(propertyInfo.PropertyType);
                // Set binding for selected item
                object value = propertyInfo.GetValue(foodEnumerationCollection, null);
                Binding binding2 = new Binding();
                binding2.Source = propertyInfo;
                binding2.Path = new PropertyPath(propertyInfo.Name);
                binding2.Mode = BindingMode.TwoWay;
                binding2.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
                comboBox.SetBinding(ComboBox.SelectedItemProperty, binding2);
                this.FoodMenu.Items.Add(comboBox);
            }
}

INotifyPropertyChanged在使用反射动态绑定时不起作用

PropertyInfo类没有实现INotifyPropertyChanged,而你正在将Source设置为PropertyInfo的一个实例

我敢肯定这一行就是罪魁祸首:

binding2.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;

只有当你通过调用UpdateSource()显式地告诉Binding对象更新时,它才会更新绑定。

你可以省略这行来使用默认值,它应该工作得很好…并听取了Erno的回答