【发布时间】:2016-06-14 10:00:15
【问题描述】:
我在DataGrid 中的DataGridComboBoxColumn 中有一个DataGridComboBoxColumn,在这样的WPF 项目集中:
<DataGridComboBoxColumn Header="Master" SelectedItemBinding="{Binding MasterId}" SelectedValueBinding="{Binding Id}" DisplayMemberPath="Id" ItemsSource="{Binding Masters}" />
但是当我运行项目时,该列仅显示空白值,并且编辑模式下的组合框执行相同的操作。
DataGrid 是这样设置的:
<DataGrid Name="ReadersGrid" Grid.Row="0" Grid.Column="0" Margin="3" ItemsSource="{Binding Readers}" CanUserAddRows="True" CanUserDeleteRows="True" AutoGenerateColumns="False">
还有这样的 UserControl:
<UserControl x:Class="SmartAccess.Tabs.ReadersTab"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:SmartAccess.Tabs"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" DataContext="{StaticResource ReadersListViewModel}">
和其他列,只有文本,工作正常。
ViewModel 具有这些属性
public ObservableCollection<ReaderViewModel> Readers { get; set; }
public IEnumerable<ReaderViewModel> Masters => Readers.Concat(new List<ReaderViewModel> { new ReaderViewModel { Id = -1 } }).OrderBy(t => t.Id);
集合视图模型具有这些属性
public long Id { get; set; }
public long MasterId { get; set; }
我显示Id只是为了测试,将来会添加描述属性。
为什么 ComboBoxColumn 不起作用?
【问题讨论】:
-
我没有看到任何问题。建议您阅读stackoverflow.com/help/mcve 以获取有关如何提出此类问题的建议。欢迎来到 Stack Overflow!
-
可能存在绑定问题,查看您正在运行的项目的输出窗口,它应该会告诉您哪些属性没有找到,以及它在哪里寻找它们。
-
@omerts 错误是这样的:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Masters; DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=24534150); target property is 'ItemsSource' (type 'IEnumerable')但我不明白 -
Masters不是ReaderViewModel的属性,ReaderViewModel是单元格的 DataContext。您需要列的 ItemsSource 的 RelativeSource 绑定。 -
@icebat 谢谢,但我不明白如何从 VM 获取
Masters属性。我试过了,但它不起作用:<DataGridComboBoxColumn Header="Master" SelectedItemBinding="{Binding MasterId}" SelectedValueBinding="{Binding Id}" DisplayMemberPath="Id" ItemsSource="{Binding DataContext.Masters, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ReadersTab}}}" />