我正在尝试在 WPF 数据网格中包含一个 ComboBox 列。我正在尝试将此列绑定(bind)到 ViewModel 中的可观察集合,但是,在运行时单元格保持为空。数据上下文是正确的,因为所有普通列都成功绑定(bind)。我想在 UI 中显示“regionShortCode”。这是我的xml:
<DataGridComboBoxColumn Header="Region" DisplayMemberPath="regionShortCode" Width="SizeToHeader">
<DataGridComboBoxColumn.ElementStyle>
<Style>
<Setter Property="ComboBox.ItemsSource" Value="{Binding Path=MembershipsCollection}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style>
<Setter Property="ComboBox.ItemsSource" Value="{Binding Path=MembershipsCollection}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
& 这是我在 ViewModel 中声明的 ObservableCollection。从构造函数中调用的方法成功填充集合:
private ObservableCollection<tbAccountMembership> _MembershipsCollection;
public ObservableCollection<tbAccountMembership> MembershipsCollection
{
get { return _MembershipsCollection; }
set
{
_MembershipsCollection = value;
OnPropertyChanged("MembershipsCollection");
}
}
在运行时我得到:
System.Windows.Data Error: 40 : BindingExpression path error: 'MembershipsCollection' property not found on 'object' ''tbAccountMembership_041E43AFC29975F12C156BA1373ACD47FC07BBE55614E5AF8AD3BBD9F090C133' (HashCode=46247020)'. BindingExpression:Path=MembershipsCollection; DataItem='tbAccountMembership_041E43AFC29975F12C156BA1373ACD47FC07BBE55614E5AF8AD3BBD9F090C133' (HashCode=46247020); target element is 'TextBlockComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
在输出窗口中。为什么 Xaml 无法解析此绑定(bind)?谢谢
最佳答案
如果您想从 DataGrid
数据绑定(bind)到 View 模型中的单个集合属性,那么您对为什么 Xaml 无法解析此绑定(bind)的回答?是因为您没有告诉框架在哪里查找实际属性...您需要使用 [RelativeSource Binding
] 1 .试试这个:
<DataGridComboBoxColumn Header="Region" DisplayMemberPath="regionShortCode"
Width="SizeToHeader">
<DataGridComboBoxColumn.ElementStyle>
<Style>
<Setter Property="ComboBox.ItemsSource" Value="{Binding
DataContext.MembershipsCollection, RelativeSource={RelativeSource
AncestorType={x:Type YourViewModelsPrefix:YourViewModel}}}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style>
<Setter Property="ComboBox.ItemsSource" Value="{Binding
DataContext.MembershipsCollection, RelativeSource={RelativeSource
AncestorType={x:Type YourViewsPrefix:YourView}}}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
有了这个
Binding Path
,框架将看起来超出正常 DataGrid.DataContext
对于名为 MembershipsCollection
的属性在设置为 DataContext
的对象中的YourView
(显然这不是实际名称)UserControl
或 Window
.如果 y 我们的 View 模型被正确设置为 DataContext
那么这应该可以正常工作。
关于c# - WPF DataGridComboBoxColumn 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25644003/