在寻求有关此主题的帮助时,我通常会找到有关如何用相关数据填充ComboBox的信息(在一个表中显示源表中的外键的名称),但是我已经能够做到这一点。我正在寻找有关如何在TextBlock中实现相同结果的解决方案。
在我的项目中,我使用EntityFramework创建了到SQL数据库的链接。有两个表:人员和角色。它们与Personnel.RoleIdFk和Role.RoleId相关。
我能够获得一个组合框,以显示关联的RoleIdFk的Role.RoleName。
在我的ViewModel中:
private ICollection<Role> roleList;
public ICollection<Role> RoleList
{
get { return roleList; }
set { roleList = value; NotifyPropertyChanged("RoleList"); }
}
private Role selectedRole;
public Role SelectedRole
{
get { return selectedRole; }
set { selectedRole = value; NotifyPropertyChanged("SelectedRole"); }
}
public void SetSelectedRole()
{
if (SelectedPerson == null)
{
SelectedPerson = PersonnelList.Select(p => p)
.FirstOrDefault();
}
SelectedRole = RoleList.Where(p => p.RoleId == SelectedPerson.RoleIdFk)
.FirstOrDefault();
}
以及ComboBox的XAML:
<ComboBox x:Name="cboRole"
Grid.Column="1" Grid.Row="0"
Width="150" Height="35"
ItemsSource="{Binding RoleList}"
DisplayMemberPath="RoleName"
SelectedItem="{Binding SelectedRole}"
/>
我的问题是我还在为人员表显示一个DataGrid。在此DataGrid中,我希望显示关联的RoleName而不是数字外键。DataGrid
当前的XAML:
<Window.DataContext>
<viewModel:MainWindowVM />
</Window.DataContext>
<ListView Name="lstPersonnel"
Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1"
ItemContainerStyle="{StaticResource ItemContStyle}"
ItemsSource="{Binding PersonnelList}" >
<ListView.View>
<GridView>
<GridViewColumn Width="75" Header="First Name" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding FirstName}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="75" Header="Last Name" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding LastName}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="75" Header="Role" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding RoleIdFk}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
这是网格的样子:
对于最后一列,我尝试以各种方式更改文本字段。我也尝试过使用其他模板和样式。这些都没有成功。
有没有一种方法可以在XAML本身中实际执行此操作,还是我必须设置某种值转换器来完成此操作?
注意:我曾经考虑过使用某种“开关/案例”方案。尽管它在这里可以工作,但我需要找出一些可以更加动态化的东西。在项目的稍后部分,我将需要将PersonnelId与其他项目相关联。“切换/案例”方案对于300多个人员来说是不可行的。
“角色”应该在“人员”对象中可用。因此,您可以简单地使用“ Role.RoleName”而不是“ RoleIdFk”:
<TextBlock Text="{Binding Role.RoleName}" />
在没有引用对象的情况下,最好将两个集合连接起来并使用结果作为DataGrid的ItemsSource。这是一个示例:在一个数据网格中联接两个表usig Linq C#WPF
IMultiValueConverter也有一个解决方案,但似乎过于复杂:使用多重绑定将2个集合连接到datagrid中
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句