【发布时间】:2013-04-17 04:08:32
【问题描述】:
我正在尝试将数据绑定到组合框。数据来自名称为 tbltest 的数据库表,表有 2 个字段 id 和 name。
当我尝试将名称绑定到组合框时,它会在视图中显示 tbltest:name。我正在使用域服务和 MVVM 来绑定数据。
下面是我的 ViewModel 代码:
public ViewModel()
{
var query = context.GetTblTestsQuery();
var load = context.Load(query);
load.Completed += (s, ea) =>
{
ObsCompanyCollection = new ObservableCollection<tblTest>(context.tblTests);
};
}
private ObservableCollection<tblTest> _ObsCompanyCollection = new ObservableCollection<tblTest>();
public ObservableCollection<tblTest> ObsCompanyCollection
{
get
{
return _ObsCompanyCollection;
}
set
{
if (_ObsCompanyCollection != value)
{
_ObsCompanyCollection = value;
NotifyPropertyChanged("ObsCompanyCollection");
}
}
}
下面是我的 XAml 文件的代码:
<UserControl.Resources>
<my:ViewModel x:Key="ViewModel"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource ViewModel}">
<ComboBox Height="23" HorizontalAlignment="Left" Margin="47,128,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" DisplayMemberPath="{Binding name,Mode=TwoWay}" ItemsSource="{Binding ObsCompanyCollection,Mode=TwoWay}" SelectedItem="{Binding tbldata.SelectCompanyId,Mode=TwoWay}" />
我不知道这段代码有什么问题。我只想在我的组合框中显示名称。
谢谢
【问题讨论】:
-
将显示成员路径更改为,DisplayMemberPath="name"
-
感谢您的回复...工作正常,但我想将所选项目的 id 保存到另一个表 tbldata 中。那么我怎样才能获得选定项目的 ID。当我将数据保存为空时。
-
获取选中值,var x = (Your itemssource object)combobox.SelectedItem;
-
再次感谢。现在它正在工作。
标签: silverlight-4.0 silverlight-5.0