多绑定wpf组合框的SelectedValuePath和SelectedValue

时间:2013-12-11 10:18:03

标签: c# wpf binding combobox

我对wpf模板和绑定有点新鲜,这就是为什么要面对以下问题:

我们假设我的应用程序中有以下对象。

XAML:

<ComboBox Name="ComboModel" Width="230" Height="25" Grid.Row="3" Grid.Column="1"         HorizontalAlignment="Left" IsEnabled="True" >
        <ComboBox.ItemTemplate>
                  <DataTemplate>
                    <TextBlock>
                     <TextBlock.Text>
                      <MultiBinding StringFormat="{}{0}, {1}: {2}-{3}">
                       <Binding Path="ModelName"/>
                       <Binding Path="ModelBody"/>
                       <Binding Path="ModelFromYear"/>
                       <Binding Path="ModelToYear"/>
                      </MultiBinding>
                     </TextBlock.Text>
                    </TextBlock>
                   </DataTemplate>
         </ComboBox.ItemTemplate>
    </ComboBox>

CODE: Combobox绑定到ModelYearClass对象列表。

public class ModelYearClass
{
    private string modelName;
    public string ModelName
    {
        get { return modelName; }
        set
        {
            modelName = value;
        }
    }
    private string modelMake;
    public string ModelMake
    {
        get { return modelMake; }
        set
        {
            modelMake = value;
        }
    }
    private string modelBody;
    public string ModelBody
    {
        get { return modelBody; }
        set
        {
            modelBody = value;
        }
    }
    private string modelYear;
    public string ModelYear
    {
        get { return modelYear; }
        set
        {
            modelYear = value;
        }
    }
    private int modelId;
    public int ModelId
    {
        get { return modelId; }
        set
        {
            modelId = value;
        }
    }
    private string modelFromYear;
    public string ModelFromYear
    {
        get { return modelFromYear; }
        set
        {
            modelFromYear = value;
        }
    }
    private string modelToYear;
    public string ModelToYear
    {
        get { return modelToYear; }
        set
        {
            modelToYear = value;
        }
    }
}
    ...
    List<ModelYearClass> ModelYearList;
    ...
    ComboModel.ItemsSource = ModelYearList;
    ComboModel.SelectedValuePath = "@ModelId";
    ComboModel.SelectedValue = 2;

一切都很好 - 组合框中填充了我想要的东西,但是我无法通过这些线条分配我需要的值。

ComboModel.SelectedValuePath = "@ModelId";
ComboModel.SelectedValue = 2;

我想也许在某种情况下,对于带有multibindig的组合框,它可能已经完成了吗?

如何实现这一目标?请帮帮我。

1 个答案:

答案 0 :(得分:1)

只需从@移除"@ModelId"即可。

ComboModel.SelectedValuePath = "ModelId";

通常SelectedValuePath的{​​{1}}属性永远不会改变。如果是这样,请考虑在XAML中设置它。

ComboBox