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

3

我的组合框与谷歌搜索结果绑定。

<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 如何显示“查询”值而不是对象名称?

尝试使用 <ComboBox DisplayMemberPath="Query" ... />。这有帮助吗? - Anatoliy Nikolaev
3个回答

4
您尝试过在ComboBox控件中添加DisplayMemberPath属性吗?
 <ComboBox
        Style="{StaticResource ComboBoxStyle}"
        IsEditable="True"
        IsTextSearchEnabled="False"
        ItemsSource="{Binding GoogleSuggest.SuggestedQueries}"
        SelectedItem="{Binding GoogleSuggest.SelectedQuery}"
        DisplayMemberPath="Query"
        >

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


重写ToString()方法是有效的。由于ItemTemplate,DisplayMemberPath无法使用。谢谢! - Jayson Ragasa

3

这样也可以!它比重写ToString()更加符合XAML的风格。 - Jayson Ragasa

0
我认为有更简单的方法来达到你的目标,尝试一下: 只需重写你的类"Model_SuggestedQueries"的ToString()函数 :p


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接