我需要将dataGrid中的ComboBox绑定到List<string>
列表如下:
public static ObservableCollection<string> m_Category =
new ObservableCollection<string>() { "Simulation", "Materials" };
这是我的comboBox定义:
<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>
我在组合框中没有得到任何值
答案 0 :(得分:1)
试试这个
<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; }
}
......
我希望这会让你了解如何绑定静态属性
答案 1 :(得分:1)
ObservableCollection是静态的,因此您必须使用另一种语法:
ItemsSource="{Binding Source={x:Static YourClass.m_Category} ,
NotifyOnTargetUpdated=True,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
但是:这也行不通。 您只能绑定到属性,而不能绑定到字段。所以你必须创建一个属性,我不会将其定义为静态。像以下一样更改您的VM:
public static ObservableCollection<string> m_Category = new ObservableCollection<string>() { "Simulation", "Materials" };
public ObservableCollection<string> Category
{
get { return m_Category; }
}
并将您的ComboBox绑定到此属性:
<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>
当然这只有在你设置了正确的DataContext时才有效,你可以用一些像snoop
这样的wpf间谍来观看