我正在使用 MVVM 模式开发 WPF 应用程序。我在 View 中有一个组合,在 View 模型(项目和组织)中有两个列表。根据组织列表项,我必须绑定(bind)组织名称。
例如,如果组织列表的 Count 属性为 1,则组合框项目必须为 “项目名称” ,如果组织列表的 Count 属性大于 1,则组合框项应类似于 “项目名称 - 组织名称” .
这是我拥有的 XAML 代码:
<ComboBox x:Name="textBox3" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=Projects}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding Path=SelectedProject}">
</ComboBox>
我应该如何达到这个目的。我希望能有一点帮助。干杯。
我在 View 模型中添加了属性 projectFullName 但我得到了一个空的组合框:
public string ProjectFullName
{
get
{
if (this.organizations.ToList().Count > 1)
{
this.projectFullName = string.Format("{}{0} - {1}", this.selectedProject.Name, this.organizations.First(org => org.Id == this.selectedProject.OrganizationId).Name);
}
else if (this.organizations.ToList().Count == 1)
{
this.projectFullName = this.selectedProject.Name;
}
return this.projectFullName;
}
}
XAML 代码:
<ComboBox x:Name="textBox3" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=Projects}" DisplayMemberPath="{Binding Path=ProjectFullName}" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding Path=SelectedProject}">
</ComboBox>
最佳答案
你有几个选项来实现这一点,但在我看来,最好的是:
将属性添加到您的数据上下文中,将被称为“FullName”之类的。
那将返回:(伪)
如果项目数 > 0 则
返回名称 + '-' + 项目名称
否则返回名称
然后将 DisplayMemberPath 绑定(bind)到 FullName。
关于c# - 使用 MVVM 模式从 View 模型到 WPF 中的 View 的条件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30161512/