2016-02-04 41 views
0

我希望我的ComboBoxText屬性根據SelectedItem的更改爲。我已經嘗試在代碼隱藏和XAML,並已經到了這個;組合框文本沒有綁定到DataGrid SelectedItem

<ComboBox Grid.Row="6" Grid.Column="1" x:Name="contactEmployeeComboBox" Text="{Binding SelectedItem.EmployeeName, ElementName=contactsDataGrid, Mode=OneWay}" Margin="5"> 

但是Text仍然當我選擇從DataGrid另一項目不會改變。我如何正確綁定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 
} 
+0

置'文本= 「{結合SelectedItem.EmployeeName,的ElementName = contactsDataGrid,模式=雙向}」' – StepUp

+0

是它MVVM或代碼隱藏?請填寫DataGrid的'DataGrid'和'ComboBox'的代碼' – StepUp

+0

'ComboBox'沒有填充,它只有兩個項目,我硬編碼了。我已經添加了'DataGrid'的代碼雖然我認爲它是無關的... – CBreeze

回答

0

Binding.Mode Property - gets or sets a value that indicates the direction of the data flow in the binding.

試着設置爲TwoWay這樣的:

<ComboBox Text="{Binding SelectedItem.EmployeeName, ElementName=contactsDataGrid, Mode=TwoWay}"/> 

As MSDN says:

雙向。導致對源屬性或目標 屬性的更改自動更新另一個屬性。這種類型的綁定適用於可編輯的表單或其他完全交互式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> 
+0

不幸的是,除了我真的想要'OneWay',以便'DataGrid'沒有更新改變'ComboBox'。 – CBreeze

+0

@CBreeze請看我的更新回答 – StepUp

+0

@CBreeze隨時提問任何問題 – StepUp

相關問題