我正在使用课堂通话应用。它有Observable collection
名为 AvailableTypes 。我想将此AvailableTypes可观察集合绑定到wpf ComboBox
。当加载表单时,这些AppId应该加载到comboBox中。你能给我一个解决方案吗?
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 :(得分:0)
不要重载属性getter / setter。让它更简单。
我建议使用自动属性和NotifyPropertyWeaver或使用PostSharp post build编译时注入的instuctions来支持INotifyPropertyChanged接口。
这使您的视图模型更易读,易于管理/理解。
在您的表单'Loaded'事件或SL中的'NavigatedTo'中,您可以从任何地方开始加载数据,并在加载完成后设置相应的属性(在回调/事件处理程序中,不要忘记在更新时使用UI调度程序绑定属性)
答案 1 :(得分:0)
在你的xaml代码中,这是一个如何绑定到组合框的简单示例。
<ComboBox ItemsSource={Binding Path=AvailableTypes} />
您还需要将viewmodel加载到窗口的DataContext中。
var window = new MainWindow
{
DataContext = new Apps()
};
window.Show();
如果你想在App启动时打开窗口,你可以改为
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var window = new MainWindow
{
DataContext = new Apps()
};
window.Show();
}
}