简体   繁体   中英

bind a ComboBox in DataGrid to a List<string>

I need to bind a ComboBox in my dataGrid to a List<string>

the List is below:

public static ObservableCollection<string> m_Category = 
    new ObservableCollection<string>()  { "Simulation", "Materials" };

here is my comboBox definition :

<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <Grid FocusManager.FocusedElement="{Binding ElementName= taskCombo}" >
            <ComboBox x:Name="MyComboBox" Height="Auto" Width="Auto"  
            ItemsSource="{Binding m_Category ,
                         NotifyOnTargetUpdated=True,
                         Mode=TwoWay,
                         UpdateSourceTrigger=PropertyChanged}" 
            SelectedIndex ="0"  
            SelectionChanged ="MyComboBox_SelectionChanged"/>
        </Grid>
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

i did not get any values in the combobox

Try this

 <ComboBox ItemsSource="{Binding Source={x:Static Member=local:MyWindow.M_Category}}"/>

 public partial class MyWindow : MyBaseWindow
{
    public static ObservableCollection<string> m_Category = new ObservableCollection<string>() { "Simulation", "Materials" };
    public static ObservableCollection<string> M_Category
    {
        get { return m_Category; }
    }
    ......

I hope this will give you an idea how to bind static properties

the ObservableCollection is static, so you'd have to use another syntax:

ItemsSource="{Binding Source={x:Static YourClass.m_Category} ,
                     NotifyOnTargetUpdated=True,
                     Mode=TwoWay,
                     UpdateSourceTrigger=PropertyChanged}" 

But: this won't work either. You can only bind to properties, not to fields. So you have to create a property, which I would not define as static anyway. Change your VM like :

public static ObservableCollection<string> m_Category = new ObservableCollection<string>()  { "Simulation", "Materials" };
public ObservableCollection<string> Category
{
  get { return m_Category; }
}

and bind your ComboBox to this Property:

<DataGridTemplateColumn.CellEditingTemplate>
  <DataTemplate>
    <Grid FocusManager.FocusedElement="{Binding ElementName= taskCombo}" >
        <ComboBox x:Name="MyComboBox" Height="Auto" Width="Auto"  
        ItemsSource="{Binding Category}" 
        SelectedIndex ="0"  
        SelectionChanged ="MyComboBox_SelectionChanged"/>
    </Grid>
  </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

of course this will only work if you have set the correct DataContext, which you can watch with some wpf spy like snoop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM