wpf 组合框默认值为 textBlock

wpf combobox default value to textBlock

我需要在 combobox.I 中添加默认值 'select' 无法将此值添加到 database.This 位置值是 dynamic.It 出现基于用户角色。我尝试了不同的方法都没有 worked.Please 帮助。

<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>

后面的代码是 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();
            }
        }
    }

您可以使用 CompositeCollection

来实现您的目标

你可以做到。在 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>

那么您的组合框项目源将为:

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

应该可以。您还需要在资源中为 collection 定义数据模板,以定义项目的显示方式

请注意 c:SecurityContexts 中的 c 是您定义自定义 object

的路径