ComboBox文本未绑定到DataGrid SelectedItem

时间:2016-02-04 14:53:22

标签: c# wpf xaml combobox datagrid

我希望Text的{​​{1}}属性根据ComboBox的{​​{1}}进行更改。我已经尝试过代码隐藏和SelectedItem并且已经完成了这个;

DataGrid

但是当我从XAML中选择另一个项目时,<ComboBox Grid.Row="6" Grid.Column="1" x:Name="contactEmployeeComboBox" Text="{Binding SelectedItem.EmployeeName, ElementName=contactsDataGrid, Mode=OneWay}" Margin="5"> 仍然没有变化。如何正确绑定Text

编辑: DataGrid

ComboBox

1 个答案:

答案 0 :(得分: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:

  

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>