Search code examples
wpfdynamiccomboboxdefault

wpf combobox default value to textBlock


I need to add a default value 'select' in the combobox.I cant add this value to the database.This location value is dynamic.It appears based upon the userrole. I tried different ways nothing worked.Please help.

<ComboBox Width="140" ItemsSource="{Binding SecurityContexts, Mode=OneWay}"
                      SelectedItem="{Binding ActiveSecurityContext, Mode=TwoWay}"
                      ToolTip="Working Location">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Location}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

The code behind is SecurityContexts = new ObservableCollection(_currentUser.ApplicationSecurityContexts);

public interface IApplicationSecurityContext
{
    IRole Role { get; }
    string Location { get; }
    IEnumerable<string> Budgets { get; }

}

public IApplicationSecurityContext ActiveSecurityContext
    {
        get { return this._currentUser.ActiveSecurityContext; }
        set
        {
            if (this._currentUser.ActiveSecurityContext != value)
            {
                this._currentUser.ChangeActiveSecurityContext(value);

                RaisePropertyChanged("CurrentUser");

                LoadData();
            }
        }
    }

Solution

  • You can achieve your goal using CompositeCollection

    you can do this. Define resource in your grid/usercontrol/combobox:

        <Grid.Resources>
            <CollectionViewSource x:Key="cvs" Source="{Binding Binding SecurityContexts, Mode=OneWay}" />
            <DataTemplate DataType="{x:Type c:SecurityContexts}">
                 <TextBlock Text="{Binding Location}"/>
            </DataTemplate>
        </Grid.Resources>
    

    then your combobox itemsource will be:

    <ComboBox.ItemsSource>
       <CompositeCollection>
          <ComboBoxItem>
             <TextBlock Text="select"/>
          </ComboBoxItem>
          <CollectionContainer Collection="{Binding Source= {StaticResource cvs}}"/>
       </CompositeCollection>
     </ComboBox.ItemsSource>
    

    It should work. You need to define your datatemplate for your collection in the resource too, to define how your item will be displayed

    Note that c in c:SecurityContexts is the path where you defined your custom object