I am developing a WPF application using MVVM pattern. I have a combo in the view and two lists in the viewmodel (projects and organizations). Depending on the organizations list items I have to bind the the name of the organization or not. For example if the Count property of the organizations list is 1 the combobox item have to be "ProjectName" , and if the Count property of the organizations list is greater than 1 the combobox item should look like "ProjectName - OrganizationName" . This is the XAML code I have:
<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>
How should I achieve this purpose. I hope for a little help. Cheers.
I added the property projectFullName in the viewmodel but I got an empty combobox:
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 code:
<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>
you have several options to implement this, but in my opinion the best is:
Add a property to your Data Context, the will be called "FullName" or something. That will return: (Pseudo) if Projects count > 0 then return Name + '-' + ProjectName else return Name
then bind DisplayMemberPath to FullName.
Datatrigger is indeed your friend. Make sure the ComboBox does not set the DisplayMemberPath, because that will override the style setters.
<Style x:Key="MyStyle" TargetType="ComboBox">
<Setter Property="DisplayMemberPath" Value="DefaultName"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Items.Count}" Value="1">
<Setter Property="DisplayMemberPath" Value="OtherName"/>
</DataTrigger>
</Style.Triggers>
</Style>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.