我在一个 WPF 项目中有一个 DataGridComboBoxColumn,设置如下:
<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 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 没有工作?
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')
,但我不理解。 - Matteo BruniMasters
不是ReaderViewModel
的属性,而它是单元格的 DataContext。你需要使用列的 ItemsSource 的相对源绑定。 - icebat<DataGridComboBoxColumn Header="Master" SelectedItemBinding="{Binding MasterId}" SelectedValueBinding="{Binding Id}" DisplayMemberPath="Id" ItemsSource="{Binding DataContext.Masters, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ReadersTab}}}" />
- Matteo Bruni