WPF:在ComboBox中使用属性字段值而不是对象名称

时间:2013-07-17 07:29:21

标签: wpf wpf-controls

大家好,我的组合框与谷歌搜索结果绑定。

<ComboBox
    Style="{StaticResource ComboBoxStyle}"
    IsEditable="True"
    IsTextSearchEnabled="False"
    ItemsSource="{Binding GoogleSuggest.SuggestedQueries}"
    SelectedItem="{Binding GoogleSuggest.SelectedQuery}"
    >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>

                <Image Source={Binding IconPath, Converter={StaticResource IconPathToImageSource} Width="32" Height="32" />

                <StackPanel Grid.Column="1">
                    <TextBlock Text="{Binding Query}" Margin="0,8" FontSize="24" />
                    <TextBlock Text="{Binding URL}" Margin="0,8" FontSize="16" />
                </StackPanel>
            </Grid>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我的模型看起来像这样

public class Model_SuggestedQueries : ViewModelBase
{
    private string _Query = string.Empty;
    public string Query
    {
        get { return _Query; }
        set
        {
            if (_Query != value)
            {
                _Query = value;
                base.RaisePropertyChanged("Query");
            }
        }
    }

    private int _Index = 0;
    public int Index
    {
        get { return _Index; }
        set
        {
            if (_Index != value)
            {
                _Index = value;
                base.RaisePropertyChanged("Index");
            }
        }
    }

    private string _URL = 0;
    public string URL
    {
        get { return _URL; }
        set
        {
            if (_URL != value)
            {
                _URL = value;
                base.RaisePropertyChanged("URL");
            }
        }
    }

    private string _Icon = 0;
    public string Icon
    {
        get { return _Icon; }
        set
        {
            if (_Icon != value)
            {
                _Icon = value;
                base.RaisePropertyChanged("Icon");
            }
        }
    }
}

但是当我做出选择时,.Text字段看起来像这样。

enter image description here

如何显示“查询”值而不是对象名称?

3 个答案:

答案 0 :(得分:4)

您是否尝试将 DisplayMemberPath 属性添加到ComboBox控件?

 <ComboBox
        Style="{StaticResource ComboBoxStyle}"
        IsEditable="True"
        IsTextSearchEnabled="False"
        ItemsSource="{Binding GoogleSuggest.SuggestedQueries}"
        SelectedItem="{Binding GoogleSuggest.SelectedQuery}"
        DisplayMemberPath="Query"
        >

如果它不起作用,您可以尝试覆盖 Model_SuggestedQueries 类的 ToString()方法。

答案 1 :(得分:3)

TextSearch.TextPath="Query"添加到您的ComboBox标记。

请参阅MSDN Textsearch.Textpath

答案 2 :(得分:0)

我认为有一种更简单的方法可以实现您的目标,请尝试以下操作: 只需重写类“ Model_SuggestedQueries”的ToString()函数 :p

相关问题