上下文:我正在使用 EF 5 并尝试将两个实体绑定到 WPF 表单。它适用于简单的属性到文本框绑定,但我想将导航属性对象绑定到组合框。我正在学习 WPF,所以这可能很明显。
我有两个 EF 实体:
Product { int Id, string Name, Category Category }
和
Category { int Id, string Description }
我制作了一个 WPF 表单来创建和编辑产品,它是这样的(简化):
<Window.Resources>
<CollectionViewSource x:Key="productViewSource" d:DesignSource="{d:DesignInstance my:product, CreateList=True}" />
<CollectionViewSource x:Key="categoryViewSource" d:DesignSource="{d:DesignInstance my:category, CreateList=True}" />
</Window.Resources>
<Grid DataContext="{StaticResource productViewSource}">
<Label Content="Id" Height="28" HorizontalAlignment="Left" Margin="6,6,0,0" Name="label1" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="61,8,0,0" Name="txtId" Text="{Binding Path=Id, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Top" Width="56" IsEnabled="False" />
<Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="6,38,0,0" Name="label2" VerticalAlignment="Top" />
<TextBox Text="{Binding Path=Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" Height="23" HorizontalAlignment="Left" Margin="61,40,0,0" Name="txtNome" VerticalAlignment="Top" Width="183" IsEnabled="False" />
<Label Content="Category" Height="28" HorizontalAlignment="Left" Margin="6,129,0,0" Name="label5" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="72,132,0,0" Name="comboCategory" VerticalAlignment="Top" Width="172"
DisplayMemberPath="Description"
SelectedValuePath="Id"
SelectedValue="{Binding Path=Category, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding Path=categoryViewSource, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">
</ComboBox>
</Grid>
加载两个视图源的代码是这样的:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
context = new DBEntities();
var productViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("productViewSource")));
context.Product.Include(p => p.Category);
context.Product.Load();
ProductViewSource.Source = context.Product.Local;
var categoryViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("categoryViewSource")));
categoryViewSource.Source = context.Category.ToList();
}
当窗口加载时,两个文本框工作,但组合框始终为空。
可能这就是问题所在,但我似乎无法找到使其工作的方法。
ItemsSource="{Binding Path=categoryViewSource, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"