[英]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.