我有这段代码:
public partial class MainWindow : Window {
SqlConnection conn;
DataTable dataTable;
SqlDataAdapter adapter;
public MainWindow() {
try {
InitializeComponent();
this.conn = new SqlConnection("Server=(LocalDB)\\v11.0; Database = usersdb; Integrated Security=True; MultipleActiveResultSets=True");
this.conn.Open();
this.dataTable = new DataTable();
adapter = new SqlDataAdapter("Select Forenames, Surname from users", conn);
new SqlCommandBuilder(adapter);
adapter.Fill(this.dataTable);
this.DataContext = this.dataTable;
TextBox textBox= new TextBox { };
Binding binding = new Binding("forenames");
binding.Mode = BindingMode.TwoWay;
binding.ValidatesOnDataErrors = true;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
textBox.SetBinding(TextBox.TextProperty, binding);
}
我在XAML中也有这个:
<ListBox ItemsSource="{Binding}" DisplayMemberPath="forenames" Name="listBox" Width="200" DockPanel.Dock="Left" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch"/>
如何绑定文本框以显示列表中当前选定的人?
答案 0 :(得分:0)
您好,以显示您需要在VM
private DataRow _selectedPerson;
public DataRow SelectedPerson
{
get { return _selectedPerson;}
set { _selectedPerson = value; OnPropertyChanged("SelectedPerson");}
}
您的get
应该返回名称和姓氏以及xaml
<ListBox ... SelectedValue="{Binding SelectedPerson}"/>
<TextBlock Text="{Binding SelectedPerson, Converter={StaticResource dtRow2Text}}"/>
和您的Converter
public class DataRow2String: IValueConveter
{
public object Convert(object value, Type targetType, object paramater, CultureInfo culture)
{
var dt = value as DataRow;
return (dt[index with names] +" "+ dt[index with surname]).ToString();
}
}
HTH
答案 1 :(得分:0)
谢谢,我终于使用:
实现了它private void selectionChanged(object sender, SelectionChangedEventArgs e) {
int index = this.listBox.SelectedIndex;
if (index < 0 || index > this.dataTable.Rows.Count)
return;
UIElementCollection collection = this.grid.Children;
foreach (UIElement element in collection)
if (element is TextBox) {
TextBox t = (TextBox)element;
t.DataContext = this.dataTable.DefaultView[index];
}
}