[英]Get ComboBox Selected Item
<ComboBox ItemsSource="{Binding Path=TUserDS}" x:Name="UserCB"
SelectionChanged="UserCB_SelectionChanged" Width="200"
HorizontalAlignment="left" SelectedIndex="0" Padding="2" Margin="0 10 0 0">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=UserName}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
loadUserCB();
}
private void loadUserCB()
{
SqlDbConnect sdc = new SqlDbConnect();
DataSet ds = new DataSet();
sdc.SqlQuery("select * from TUser");
ds=sdc.QueryEx("TUserDS");
UserCB.DataContext = ds;
string selUserName = UserCB.SelectedItem.ToString(); //this code failed to get the selected item
}
}
}
在MainWindow.xaml中,我创建了一个组合框,然后在MainWindow.xaml.cs中,将组合框与Sqlserver中的表绑定在一起。 如何从UserCB组合框中获取所选项目?
我认为您应该尝试使用MVVM框架。
由于绑定是基于通知而不是活动的,因此在非MVVM框架的情况下,如果直接修改DataContext。 所有已绑定的属性将不知道DataContext已更新,因此它们的价值不会改变。
通过MVVM框架,使用实现INotifyPropertyChanged接口的ViewModel可以在属性更改时通知所有相关的绑定属性,从而避免了DataContext更新的问题。
简单的例子:
//C# Code
//Define a ViewModel
public class VM : INotifyPropertyChanged
{
private DataSet _ds;
public event PropertyChangedEventHandler PropertyChanged;
public DataSet Ds
{
get => _ds;
set
{
_ds = value;
//Notify: Property "Ds" updated
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Ds"));
}
}
}
public MainWindow()
{
DataContext = new VM();
//set viewmodel to DataContext before InitializeComponent
InitializeComponent();
loadUserCB();
}
<!--Xaml Code-->
<!-- V Note here.*-->
<ComboBox ItemsSource="{Binding Tables[TUserDS]}"
x:Name="UserCB"
SelectionChanged="UserCB_SelectionChanged"
Width="200"
HorizontalAlignment="left"
SelectedIndex="0"
Padding="2"
Margin="0 10 0 0">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding UserName}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
*:DataSet不支持索引器,但“ DataSet.Tables”支持索引器。
由于ComboBox.ItemsSource收到了VM.Ds属性更改的通知,因此它将尝试更新自己的数据
如果您要坚持当前的设计,请尝试将Xaml更改为
<ComboBox ItemsSource="{Binding Path=TUserDS}" x:Name="UserCB" SelectionChanged="UserCB_SelectionChanged" Width="200"
HorizontalAlignment="left" SelectedIndex="0" Padding="2" Margin="0 10 0 0"
DisplayMemberPath="UserName"/>
更多信息在这里
在这种情况下,您的名称为ComboBox-> UserCB
在类MainWindow
:
UserCB.SelectedItem
UserCB.SelectedIndex
。 如果列表较小,则可以通过这种方式下载索引,并在此基础上从项目集合或项目数据库中读取值 (当您使用此内容调用函数时,将获得当前值)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.