2013-03-05 137 views
0

我有类调用应用程序。它有Observable collection调用AvailableTypes。我想将此AvailableTypes可观察集合绑定到wpf ComboBox。当表单被加载时,这些AppId应该加载到comboBox ..你能给我一个解决方案吗?将observerbaleCollection绑定到wpf组合框

class Apps: INotifyPropertyChanged{ 

    ServiceReference1.AssetManagerServiceClient client; 
    ObservableCollection<string> availableType; 
    public ObservableCollection<string> AvailableTypes 
    { 
     get 
     { 
      if (availableType == null) 
      { 
       availableType = new ObservableCollection<string>(); 

      } 
      client = new ServiceReference1.AssetManagerServiceClient(); 
      List<string> AssestList = client.GetAppIds().ToList<string>(); 

      foreach (string appid in AssestList) 
      { 
       availableType.Add(appid); 
      } 
      return availableType; 

     } 
     set 
     { 
      availableType = value; 
      NotifyPropertyChanged("AvailableTypes"); 

     } 
    } 


    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 
} 

回答

0

在您的xaml代码中,这是一个简单的示例,说明如何绑定到组合框。

<ComboBox ItemsSource={Binding Path=AvailableTypes} /> 

您还需要将视图模型加载到窗口的DataContext中。

var window = new MainWindow 
{ 
    DataContext = new Apps() 
}; 
window.Show(); 

如果你想打开应用程序启动时的窗口中,你可以做到这一点,而不是

public partial class App : Application 
{ 
    protected override void OnStartup(StartupEventArgs e) 
    { 
     base.OnStartup(e); 


     var window = new MainWindow 
     { 
      DataContext = new Apps() 
     }; 

     window.Show(); 
    } 
} 
0

请勿重载属性获取器/设置器。让它更简单。

我推荐使用自动属性和NotifyPropertyWeaver或使用PostSharp后构建编译时注入的instuctions来支持INotifyPropertyChanged接口。

这使得您的视图模型更具可读性并易于管理/理解。

在你的表单'Loaded'事件或SL中的'NavigatedTo'中,你可以从你想要的任何地方开始加载数据并在加载完成后设置相应的属性(在回调/事件处理程序中,不要忘记使用UI调度程序while更新绑定的属性)