[英]C# WPF DataGrid: DataGridComboxBoxColumn Binding ItemsSource failed
i want to display a ComboBox
on my DataGrid
. 我想在我的
DataGrid
上显示一个ComboBox
。 But the ComboBox
does not load the ObservableCollection
. 但是
ComboBox
不会加载ObservableCollection
。 My ObservableCollection
'Projects' is on my ViewModel defined. 我的
ObservableCollection
'在我定义的ViewModel上。 The problem is not the DataContext
. 问题不在于
DataContext
。 But when I define the ComboBox
outside of my DataGrid
, the binding works. 但是,当我在
DataGrid
之外定义ComboBox
时,绑定起作用。 Does anyone have an idea where my problem is? 有谁知道我的问题在哪里?
ViewModel: ViewModel:
public Project SelectedProject
{
get { return _project; }
set
{
if (_project != value)
{
_project = value;
OnPropertyChanged();
_actions = _database.LoadActions(SelectedProject.Id);
OnPropertyChanged(() => Actions);
}
}
}
public ObservableCollection<Project> Projects
{
get { return _database.LoadProjects(); }
}
XAML: XAML:
<DataGridComboBoxColumn Header="Projekt:" Width="140" DisplayMemberPath="Name">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Projects, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
<Setter Property="SelectedItem" Value="{Binding SelectedProject, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Projects, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
<Setter Property="SelectedItem" Value="{Binding SelectedProject, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<Setter Property="IsDropDownOpen" Value="True" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
Try this: 尝试这个:
<Setter Property="ItemsSource" Value="{Binding DataContext.Projects, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
The DataContext
of the ComboBox
in a DataGridComboBoxColumn
is the corresponding object in the DataGrid
's ItemsSource
. DataGridComboBoxColumn
中的ComboBox
的DataContext
是DataGrid
的ItemsSource
的对应对象。
If your Projects
collection is defined in the view model, you need to specify a RelativeSource
for the binding to work. 如果在视图模型中定义了
Projects
集合,则需要指定一个RelativeSource
才能使绑定起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.