c# - 如何使用DataGridComboBoxColumn?

标签 c# wpf datagrid datagridcomboboxcolumn

我创建了一个 DataGrid 并以编程方式添加了一个 DataGridComboBoxColumn

public partial class MainWindow : Window
{

    private DataGridComboBoxColumn weightColumnChar = new DataGridComboBoxColumn();
    ObservableCollection<int> mComboBoxValues;
    public ObservableCollection<int> ComboBoxValues
    {
        get { return this.mComboBoxValues; }
        set { this.mComboBoxValues = value; }
    }//end property
    public MainWindow()
    {
        InitializeComponent();
        mComboBoxValues = new ObservableCollection<int>() {-1, 0, 1 };
    }//end constructor
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        weightColumnChar.Header = "Weight";
        dataGrid_Char.Columns.Add(weightColumnChar);

        weightColumnChar.ItemsSource = ComboBoxValues;
        Binding binding = new Binding();
        binding.Path = new PropertyPath(ComboBoxValues[1]);
        weightColumnChar.SelectedItemBinding = binding;
    }//end method
    private void dataGrid_Char_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }//end method
    //Opens ComboBox on first click
    private void dataGrid_Char_GotFocus(object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource.GetType() == typeof(DataGridCell))
        {
            DataGrid grd = (DataGrid)sender;
            grd.BeginEdit(e);
        }//end if
    }//end method
}//end class

我向它添加了一个 ItemsSource 并从 ObservableCollection 中检索值。

集合中的值显示在运行时。

我的问题是,如果我从 ComboBox 中选择一个值,此值不会被选中并随后显示。我做错了什么?

而且我还想选择一个默认值。它是如何工作的?

请以编程方式而非 XAML 方式进行解释!

如果有人能帮助我,那就太好了。

谢谢!!!

最佳答案

首先,您还没有显示绑定(bind)到 DataGrid 的基础集合是什么。

你需要类似 DataGrid.ItemsSource = new ObservableCollection<MyClass>(); 的东西(必须是支持变化通知的集合,所以我选择了ObservableCollection)。

其次,您正在绑定(bind) ComboBox.SelectedItemBindingComboBox.ItemsSource这是胡说八道。 ComboBox.ItemsSource是您可以选择的值的集合,ComboBox.SelectedItemBinding (我实际上会使用 ComboBox.SelectedValueBinding )是包含/表示最终值(例如 MyClass.IntProperty)的基础数据源的“路径”。因此,您从集合中选择一个值并将其分配给某个数据项(您不能将其分配回您选择的集合)。

附言!如果您以后使用类似于 KeyValuePair 的东西(例如 Id;名称)作为您的 ComboBox.ItemsSource , 然后你设置 ComboBox.SelectedValuePath = Id; ComboBox.DisplayMemberPath = Name; .在这种情况下,MyClass.IntProperty 将包含 Id 值。

关于c# - 如何使用DataGridComboBoxColumn?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12491885/

相关文章:

.net - 如何在 asp :DataGrid for CSS? 中的第一个表头上放置一个 ID

css - 为什么 Bootstrap col-xs- "Horizontal at all times"?

c# - 使用 linq 合并 2 个具有重复键的字典

c# - xml 元素列表到公共(public)基类型的数组

c# - 将数据绑定(bind)/设置源到我的 DataGrid [WPF] 的正确方法是什么

wpf - 如何在 UserControl 和父窗口之间绑定(bind) WPF 命令

c# - 绑定(bind)仅适用于第一个 TabItem

c# - ASP.NET MVC3 和 Facebook 集成

c# - 将带毫秒的 DateTime 插入 SQL Server

WPF 和 MVVM : Get values from textboxes and send it to ViewModel