开发者

Databinding with INotifyPropertyChanged instead of DependencyProperties

I have been wrestling with getting databinding to work in WPF for a little over a week. I did get valuable help here regarding the DataContext, and I did get databinding to work via DependencyProperties. While I was learning about databinding, I came across numerous discussions about INotifyPropertyChanged and how it is better than DPs in many ways. I figured that I would give it a shot and try it out.

I am using Josh Smith's base ViewModel class and my ViewModel is derived from it. However, I'm having a bit of trouble getting databinding to work, and am hoping that someone here can tell me where I'm going wrong.

In my ViewModel class, I have an ObservableCollection<string>. In my GUI, I have a combobox that is bound to this OC, i.e.

<ComboBox ItemsSource="{Binding PluginNames}" />

The GUI's DataContext is set to the ViewModel, i.e.

private ViewModel _vm;

public GUI()
{
  InitializeComponent();
  _vm = new ViewModel();
  this.DataContext = _vm;
}

and the ViewModel has the OC named "PluginNames":

public class ViewModel
{
  public ObservableCollection<string> PluginNames;  // this gets instantiated and added to elsewhere
}

When the GUI is开发者_如何学编程 loaded, a method is called that instantiates the OC and adds the plugin names to it. After the OC is modified, I call RaisePropertyChanged( "PluginNames"). I was expecting that since the WPF databinding model is cognizant of INotifyPropertyChanged, that this is all I needed to do and it would "magically work" and update the combobox items with the plugins that got loaded... but it doesn't.

Can someone please point out what I've done wrong here? Thanks!

UPDATE: I'm not sure why, but now instead of not doing any apparent updating, it's not finding the property at all. I think I'm being really stupid and missing an important step somewhere.


When you're working with INotifyPropertyChanged, there are two things:

  1. You'll need to use properties, not fields
  2. You should always raise the property changed event when you set hte properties.

You'll want to rework this so it looks more like:

private ObservableCollection<string> pluginNames;
public ObservableCollection<string> PluginNames
{
    get { return pluginNames; }
    set {
        this.pluginNames = value;
        RaisePropertyChanged("PluginNames"); // This should raise the PropertyChanged event - use whatever your VM class does for this
    }
}

That should cause everything to repopulate.


It looks like you've exposed field not property. Bindings works for properties only... Change it to:

public class ViewModel
{
  public ObservableCollection<string> PluginNames {get; private set;} 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜