WPF组合框上的选定项目

时间:2013-01-30 11:53:13

标签: wpf xaml combobox selecteditem selectedvalue

我有一些wpf组合框(xaml):

<ComboBox ItemsSource="{Binding Path=NonPositionedConcentrators}"
          SelectedValue="{Binding Path=SelectedNonPositionedConcentrator}"
          DisplayMemberPath="SerialNumber" />

SelectedNonPositionedConcentrator - 是集中器类型。类似的东西:

class Concentrator
{
...
public string SerialNumber {...}
...
public override ToString{ return "Some needed text..."; }
}

NonPositionedConcentrators - 集中器对象列表。

因此,在应用程序中,我看到组合框的序列号为NonPositionedConcentrators(因为DisplayMemberPath="SerialNumber"),但是当我选择某个内容,然后选择项目shonw为"Some needed text..."时,请看图像:

enter image description here

我尝试过SelectedValuePath =“SerialNumber”,但它不起作用...... 我无法删除 - public override ToString{ return "Some needed text..."; },因为我需要......

3 个答案:

答案 0 :(得分:2)

看起来你有一个自定义的ComboBox模板可能会导致你的问题。如果它使用TextBlock或ContentPresenter来显示所选项目,它只是绑定SelectedItem属性而不是拉入任何模板或其他设置,那么无论如何都只能得到ToString值。正确构造的模板将具有类似于默认模板在此位置使用的内容:

<ContentPresenter ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
    Content="{TemplateBinding SelectionBoxItem}" ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}"
    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" IsHitTestVisible="false" Margin="{TemplateBinding Padding}"
    SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>

答案 1 :(得分:0)

试试这个:

<ComboBox ItemsSource="{Binding Path=NonPositionedConcentrators}"
      SelectedItem="{Binding Path=SelectedNonPositionedConcentrator}"
      DisplayMemberPath="SerialNumber" />

修改 我再现了你的例子。我的集中器课程:

public class Concentrator
{
    public string SerialNumber
    {
        get
        {
            return "123";
        }
    }
    public override string ToString()
    {
        return "Some needed text...";
    }
}

我的ViewModel:

public class TestViewModel : ViewModelBase
{
    public ObservableCollection<Concentrator> NonPositionedConcentrators { get; set; }
    public Concentrator SelectedNonPositionedConcentrator { get; set; }
    public TestViewModel()
    {
        NonPositionedConcentrators = new ObservableCollection<Concentrator>();
        NonPositionedConcentrators.Add(new Concentrator());
        NonPositionedConcentrators.Add(new Concentrator());
        NonPositionedConcentrators.Add(new Concentrator());
    }
}

组合框:

    <ComboBox Height="23" Margin="25,12,103,0" Name="comboBox1" VerticalAlignment="Top" 
              ItemsSource="{Binding Path=NonPositionedConcentrators}"
              SelectedItem="{Binding Path=SelectedNonPositionedConcentrator}"
              SelectedValuePath="SerialNumber"
              DisplayMemberPath="SerialNumber" />

它对我来说很好用!

答案 2 :(得分:-1)

您可以添加商品模板:

       <ComboBox.ItemTemplate>
            <DataTemplate>
                //your stuff
            </DataTemplate>
        </ComboBox.ItemTemplate>