【问题标题】:datagridcomboboxcolumn binding in code代码中的datagridcombobox列绑定
【发布时间】:2015-11-19 03:52:35
【问题描述】:

我想完全在代码中执行此操作,而不是 XAML: 给定的是

DataGridComboBoxColumn myDGCBC = new DataGridComboBoxColumn();
ObservableCollection<string> DataSource = new ObservableCollection<string>{"Option1", "Option2"};
myDGCBC.ItemsSource = DataSource;

ObservableCollection<MyStructure> MyObject = new ObservableCollection<MyStructure>;

public class MyStructure
{
   ... several properties ... // pseudocode, obviously
   public string SelectedValue { get; set; }
}

我有兴趣(绑定)将列中所有组合框的选定值接收到SelectedValue 属性中。

我尝试了 SO 的几个想法,但无济于事。

帮助! 谢谢。

【问题讨论】:

  • @Bahman_Aries,感谢您的编辑。从另一台计算机复制时输入错误。

标签: wpf binding datagrid datagridcomboboxcolumn programmatically-created


【解决方案1】:

假设 DataGird 已经在 xaml 中定义,您应该为 DataGridDataGridComboBoxColumn 设置正确的绑定。

这里有一个例子给你一个想法:

Xaml:

<Grid >
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <DataGrid x:Name="myGrid" AutoGenerateColumns="False"/>
    <Button Grid.Row="1"  Content="test" Click="Button_Click"/>
</Grid>

MainWindow.cs:

    //DataGrid ItemsSource
    public ObservableCollection<MyStructure> DataSource { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;

        // Initializing DataGrid.ItemsSource
        DataSource = new ObservableCollection<MyStructure>();
        DataSource.Add(new MyStructure());

        // Creating new DataGridComboBoxColumn 
        DataGridComboBoxColumn myDGCBC = new DataGridComboBoxColumn();
        myDGCBC.Header = "cmbColumn";

        // Binding DataGridComboBoxColumn.ItemsSource and DataGridComboBoxColumn.SelectedItem
        var cmbItems = new ObservableCollection<string> { "Option1", "Option2" };
        myDGCBC.ItemsSource = cmbItems;
        myDGCBC.SelectedItemBinding = new Binding("SelectedValue");
        // Adding DataGridComboBoxColumn to the DataGrid
        myGrid.Columns.Add(myDGCBC);

        // Binding DataGrid.ItemsSource 
        Binding binding = new Binding();
        binding.Source = DataSource;
        BindingOperations.SetBinding(myGrid, DataGrid.ItemsSourceProperty, binding);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        //This is just to check whether SelectedValue is set properly:
        string selectedValue = DataSource[0].SelectedValue;
    }

【讨论】:

  • 首先,谢谢。如果没有 MVVM,您愿意这样做吗?
  • 其实根本就不是Mvvm! :) 但是我修改了我的答案并删除了一些不必要的部分。请看一下并告诉我它是否有帮助。
  • myDGCBC.SelectedItemBinding = new Binding("SelectedValue");myDGCBC.SelectedValueBinding = new Binding("SelectedValue");?
  • 不客气,顺便说一句,SelectedItemBindingSelectedValueBinding 都有效,具体取决于需要。
猜你喜欢
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 2011-07-10
相关资源
最近更新 更多