Reputation: 25
In a WPF ComboBox I need to be able to display a SelectedValue that does not exist in the bound ItemsSource collection.
I've done a fair amount of searching and the only solution I've found so far is to instead bind to Text property and set IsEditable="True". I did use that in another part of my application but that won't work here because I can't risk the user providing invalid data.
In the XAML, the ItemsSource is bound to an ObservableCollection of available WorkEfforts. This list can change over time with items dropping out of the list. The SelectedValue is bound to the property of the SelectedItem on a datagrid, Title.WorkEffort. A title is a seperate task, or change, that has a work effort assigned to it. Once assigned to a Title it shouldn't change, even if the work effort is no longer active.
XAML:
<ComboBox ItemsSource="{Binding Path=WorkEfforts}"
SelectedValue="{Binding Path=Title.WorkEffort}"
DisplayMemberPath="WorkEffortString"
SelectedValuePath="WorkEffortString"
IsEnabled="{Path=EditMode}"/>
C# Code:
ObservableCollection<WorkEffort> WorkEfforts = client.GetWorkEfforts();// Gets a list of all active work efforts from database
public class WorkEffort
{
public int WorkEffortID { get; set; }
public string WorkEffortString { get; set; }
public string ChargeNumber { get; set; }
}
ChangeTitle Title { get; set;} //SelectedItem on a DataGrid whose ItemsSource is an ObservableCollection of ChangeTitles
public class ChangeTitle
{
public int CommentID { get; set; }
public int ChangeID { get; set; }
public int TitleID { get; set; }
public string WorkEffort { get; set; }
}
Any help would be appreciated. Thanks!
Upvotes: 0
Views: 2684
Reputation: 5632
ComboBox
in readonly mode does not support displaying items that does not exist in the ItemSource
, but if you are ready for small trade of, you can achieve something similar.
If you implement INotifyPropertyChanged
on ChangeTitle
and add a boolean
property similar to IsAvailable
, and then instead of removing items from the collection WorkEfforts
, you can set the IsAvailable
to false.
Combine that with an ItemContainerStyle
for your ComboBox
similar to,
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnabled" Value="{Binding Path=IsAvailable}"></Setter>
</Style>
</ComboBox.ItemContainerStyle>
And you can show the unavailable items and at the same time prevent the users from selecting them. You'll be able to programatically select the unavailable items, but your users won't be able to select them by themselves.
Upvotes: 0
Reputation: 88
You can use Text property with IsEditable="True" and IsReadOnly="True"
there also another methods here How to display default text "--Select Team --" in combo box on pageload in WPF?
Upvotes: 5