【问题标题】:Combobox "Select Item" binding组合框“选择项目”绑定
【发布时间】:2012-01-16 17:03:13
【问题描述】:

我正在开发一些需要“选择”属性作为 WPF (c#) 中的顶部选项的组合框

目前我已经命名了组合框,然后将其填充到数组字符串后面的代码中。

<ComboBox Width="150" x:Name="cmbTitle" Margin="3" SelectedIndex="0" />

.

cmbTitle.Items.Add("Select");
foreach (var title in Constants.Title)
            cmbTitle.Items.Add(title);

我的问题是所选索引将始终偏离字符串中索引的 1。

经过研究,我发现这是一种非常史前的填充组合框的方式(WinFrom 背景)。在我看过的每个示例中,常量似乎都存储在枚举中,所以我想远离多个字符串 []。

在适应 WPF 中的“选择”选项时,将枚举绑定到组合框的最佳方法是什么? 我今天看了六个选项,我不太确定要列出哪些其他代码示例。

这是一个非常开放的问题,但我很迷茫。

提前致谢, 奥利

【问题讨论】:

  • “选择”选项是否应该可供选择,还是只是对用户的提示?如果是后者,则有a better way of doing that
  • @Joulukuusi 它应该只是对用户的提示。谢谢,这看起来很有用。

标签: c# wpf binding combobox


【解决方案1】:
  1. 可以从Enum.GetValues() 检索枚举的值,并且绑定到方法通常使用ObjectDataProvider 完成。这是获取所有 BindingMode 值的示例:

    <ObjectDataProvider x:Key="BindingModes" ObjectType="{x:Type sys:Enum}" MethodName="GetValues">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="BindingMode" />
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
    

    现在,我们可以绑定ItemsSourceComboBox

    <ComboBox ItemsSource="{Binding Source={StaticResource BindingModes}}" />
    
  2. 我们的控件需要一个新的提示属性:

    public class ExtendedComboBox : ComboBox
    {
        public static readonly DependencyProperty PromptProperty =
            DependencyProperty.Register("Prompt", typeof(string), typeof(ExtendedComboBox), new PropertyMetadata(string.Empty));
    
        public string Prompt
        {
            get { return (string)GetValue(PromptTextProperty); }
            set { SetValue(PromptTextProperty, value); }
        }
    }
    

    我们可以作弊,在我们的控件中放置一个带有提示符的TextBlock,并在选择项目时隐藏它。为此,我们用包含TextBlock 的新控件重写了控件的ControlTemplate。我从there修改了模板:

    <Style x:Key="PromptTextBlock" TargetType="{x:Type TextBlock}" >
        <Setter Property="Visibility" Value="Hidden" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding SelectedItem, RelativeSource={RelativeSource TemplatedParent}}" Value="{x:Null}">
                <Setter Property="Visibility" Value="Visible" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
    
    <Style x:Key="PromptedComboBox" TargetType="{x:Type local:ExtendedComboBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:ExtendedComboBox}">
                    <Grid>
                        <ToggleButton x:Name="DropDownToggle"
                                      HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  
                                      Margin="-1" HorizontalContentAlignment="Right"
                                      IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
                            <Path x:Name="BtnArrow" Height="4" Width="8" 
                                  Stretch="Uniform" Margin="0,0,4,0"  Fill="Black"
                                  Data="F1 M 300,-190L 310,-190L 305,-183L 301,-190 Z " />
                        </ToggleButton>
                        <ContentPresenter x:Name="ContentPresenter" Margin="6,2,25,2"
                                          Content="{TemplateBinding SelectionBoxItem}"
                                          ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                                          ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}">
                        </ContentPresenter>
                        <TextBox x:Name="PART_EditableTextBox"
                                 Style="{x:Null}"
                                 Focusable="False"
                                 Background="{TemplateBinding Background}"
                                 HorizontalAlignment="Left" 
                                 VerticalAlignment="Center" 
                                 Margin="3,3,23,3"
                                 Visibility="Hidden"
                                 IsReadOnly="{TemplateBinding IsReadOnly}"/>
                            <Popup x:Name="PART_Popup" IsOpen="{TemplateBinding IsDropDownOpen}">
                                <Border x:Name="PopupBorder" 
                                        HorizontalAlignment="Stretch" Height="Auto" 
                                        MinWidth="{TemplateBinding ActualWidth}"
                                        MaxHeight="{TemplateBinding MaxDropDownHeight}"
                                        BorderThickness="{TemplateBinding BorderThickness}" 
                                        BorderBrush="Black" Background="White" CornerRadius="3">
                                    <ScrollViewer x:Name="ScrollViewer" BorderThickness="0" Padding="1">
                                        <ItemsPresenter/>
                                    </ScrollViewer>
                                </Border>
                            </Popup>
                        <TextBlock Margin="4,3,20,3" Text="{Binding PromptText, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource PromptTextBlock}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
         </Setter>
     </Style>
    
  3. 结合起来,我们有:

    <local:ExtendedComboBox Style="{StaticResource PromptedComboBox}" Prompt="Select an item" ItemsSource="{Binding Source={StaticResource BindingModes}}" />
    

【讨论】:

    【解决方案2】:

    我认为填充 ComboBox 的最佳方式是使用 IDictionary。

    例如,您的代码隐藏:

    public YourEnum SelectedOption { get; set; }
    
    public IDictionary<string, YourEnum> Options = new Dictionary<string, YourEnum?>();
    
    Options.Add("Select", null);
    Options.Add("Option 1", YourEnum.Option1);
    ...
    Options.Add("Option N", YourEnum.OptionN);
    

    您的 xaml 文件:

    <ComboBox ItemsSource="{Binding Options, ...}" SelectedValue="{Binding SelectedOption, ...}" DisplayMemberPath="Key" SelectedValuePath="Value" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2013-12-04
      • 2014-10-09
      相关资源
      最近更新 更多