[英]ComboBox Text not Binding to DataGrid SelectedItem
我希望ComboBox
的Text
属性根据DataGrid
的SelectedItem
进行更改。 我已经在代码隐藏和XAML
进行了尝试,并且做到了这一点;
<ComboBox Grid.Row="6" Grid.Column="1" x:Name="contactEmployeeComboBox" Text="{Binding SelectedItem.EmployeeName, ElementName=contactsDataGrid, Mode=OneWay}" Margin="5">
但是,当我从DataGrid
选择另一个项目时, Text
仍然不会更改。 如何正确绑定ComboBox
?
编辑: DataGrid
private void FillContactsDataGrid()
{
var selectedCompany = dataGrid.SelectedItem as CompanyModel;
var Contacts = new ObservableCollection<ContactsModel>();
var waitWindow = new PleaseWait();
var ContactTypes = new ObservableCollection<TypeOfContact>();
var contactService = new ContactsDataService();
ContactTypes = contactService.GetContactTypesDBF();
cancelAddContactButton.Visibility = Visibility.Collapsed;
cancelUpdateContactButton.Visibility = Visibility.Collapsed;
var contactsDataService = new ContactsDataService();
Contacts = contactsDataService.HandleContactSelect(companyID);
ContactsICollectionView = CollectionViewSource.GetDefaultView(Contacts);
contactsDataGrid.ItemsSource = ContactsICollectionView;
//Contacts = await ReturnContacts(Convert.ToInt32(selectedCompany.ID)); removed as tabs were jumping back to companies
}
Binding.Mode属性-获取或设置一个值,该值指示绑定中数据流的方向。
尝试像这样设置为TwoWay
:
<ComboBox Text="{Binding SelectedItem.EmployeeName, ElementName=contactsDataGrid, Mode=TwoWay}"/>
双向。 导致对源属性或目标属性的更改以自动更新另一个。 这种类型的绑定适用于可编辑表单或其他完全交互的UI方案。
更新:
YourModel:
public class YourModel
{
public string TitleField { get; set; }
}
代码背后:
public MainWindow()
{
InitializeComponent();
FillDataGrid();
}
private void FillDataGrid()
{
ObservableCollection<YourModel> coll = new ObservableCollection<YourModel>();
for (int start = 0; start < 10; start++)
{
coll.Add(new YourModel(){TitleField="Title " +
start.ToString());
}
dataGrid.ItemsSource = coll;
comboBox.DisplayMemberPath = "TitleField";
comboBox.ItemsSource = coll;
}
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var dataGrid = e.Source as DataGrid;
var currentIndex = dataGrid.Items.IndexOf(dataGrid.CurrentItem);
comboBox.SelectedIndex= currentIndex;
}
您的XAML:
<StackPanel>
<DataGrid Name="dataGrid" SelectionChanged="dataGrid_SelectionChanged" />
<ComboBox Name="comboBox"/>
</StackPanel>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.