【问题标题】:Present a ComboBox as TextBlock in WPF/Silverlight在 WPF/Silverlight 中将 ComboBox 呈现为 TextBlock
【发布时间】:2012-12-24 17:56:17
【问题描述】:

我想将 ComboBox 显示为 TextBox(没有边框、背景、切换按钮等) - 只有当前选定的项目文本。 我喜欢这样,但我不明白如何链接 TextBlock,以便在 ComboBox 中显示当前选定的项目。

<ComboBox ItemsSource="{Binding Path=...}" SelectedValue="{Binding Path=...}" DisplayMemberPath="Name" SelectedValuePath="Id">
    <ComboBox.Template>
        <ControlTemplate>
            <TextBlock Text="{Binding ?}"></TextBlock>
        </ControlTemplate>
    </ComboBox.Template>
</ComboBox>

【问题讨论】:

    标签: wpf combobox controltemplate


    【解决方案1】:
    <ComboBox ItemsSource="{Binding Path=...}" SelectedValue="{Binding Path=...}" DisplayMemberPath="Name" SelectedValuePath="Id">
    <ComboBox.Template>
        <ControlTemplate>
            <TextBlock Text="{Binding SelectedItem.MyText,RelativeSource={RelativeSource Mode=TemplatedParent}}"></TextBlock>
        </ControlTemplate>
    </ComboBox.Template>
    

    【讨论】:

    • 此解决方案将所选项目正确显示为 TextBlock,但您无法选择新项目。
    【解决方案2】:

    您应该在ControlTemplate 中指定TargetType 并绑定到SelectionBoxItem
    使用这个:

     <ComboBox>
            <ComboBox.Template>
                <ControlTemplate  TargetType="{x:Type ComboBox}">
                    <TextBlock Text="{TemplateBinding SelectionBoxItem}" />
                </ControlTemplate>
            </ComboBox.Template>
            <ComboBoxItem Content="Item1" IsSelected="True" />
            <ComboBoxItem Content="sdff" />
      </ComboBox>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 2011-06-11
      相关资源
      最近更新 更多