2

您好,感谢您的帮助。

以下 xaml 工作得很好:

<ComboBox Name="cboCit_type"
  IsSynchronizedWithCurrentItem="True"    
  mvvm:View.FlowsWithPrevious="True"
  ItemsSource="{Binding Path=cuCodeInfo.CitTypes}"
  SelectedValuePath="code" 
  DisplayMemberPath="code" 
  Text="{Binding cit_type}"
  IsEditable="true"
  IsReadOnly="false"
  SelectedValue="{Binding Path=cit_type}">
</ComboBox>

cuCodeInfo.CitTypes 只是一个可用项目的列表。有许多公共属性,但有问题的 2 个是“代码”和“描述”。

现在,我显示了可用的代码值并且用户选择了一个。如果已经选择了一个,那么它会在页面显示时显示。这一切都很好。

因此,我认为同时显示代码和描述可能会很好。我觉得应该不会太难...

所以我删除了 DisplayMemberPath 语句并添加了一个 ItemTemplate。

当我这样做时,一切看起来都很棒,直到我尝试从列表中选择一个项目。当我这样做时,我会得到一个空字符串,而不是显示选定的代码。我已经搜索了互联网,试图找到我需要添加到 DataTemplate 来解决这个问题的一件事,但是我尝试过的一切都失败了。这是不起作用的代码:

<ComboBox Name="cboCit_type"
  IsSynchronizedWithCurrentItem="True"    
  mvvm:View.FlowsWithPrevious="True"
  ItemsSource="{Binding Path=cuCodeInfo.CitationTypes}"
  SelectedValuePath="code" 
  Text="{Binding cit_type}"
  IsEditable="true"
  IsReadOnly="false"
  SelectedValue="{Binding cit_type}">

  <ComboBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal" >
            <Border BorderThickness="0,0,1,0" BorderBrush="Black">
                <TextBlock Text="{Binding Path=code}" mvvm:View.WidthEx="2" ></TextBlock>
            </Border>
            <TextBlock Text="{Binding Path=description}" mvvm:View.WidthEx="15" Margin="1" ></TextBlock>
        </StackPanel>
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

任何帮助将不胜感激。

顺便说一句,我必须在多种形式中使用这种完全相同的格式(相同的列表等,只是不同的 SelectedValue)——所以如果你想建议在 xaml 中执行此操作的最佳方法,那就太好了。在我之前的 xaml 时代,我只会创建一个控件,设置一个属性或 2,然后在我的所有表单中使用它。但我应该使用 xaml,所以不确定最好的方法。

谢谢!

4

2 回答 2

2

我不敢相信我在网上搜索了所有答案,直到现在都找不到答案。答案和我想的一样简单。

只需将: DisplayMemberPath="code" 替换为 TextSearch.TextPath="code" ,代码就可以正常工作。

感谢所有帮助过的人。

于 2013-08-13T14:41:26.703 回答
1

我可以告诉你如何使用 SelectedItem

视图模型

public class ViewModel
    {
        public ViewModel()
        {
            //Suppose your collection CitTypes is Initialized and filled with there Items
            //Now you can set first Element as selected in ComboBox 
            SelectedItem = CitTypes.FirstOrDefault();
        }

        CitType selectedItem;
        public CitType SelectedItem
        {
            get { return selectedItem; }
            set { selectedItem = value; RaisePropertyChanged("SelectedItem"); }
        }
    }

xml

<ComboBox Name="cboCit_type"
IsSynchronizedWithCurrentItem="True"    
mvvm:View.FlowsWithPrevious="True"
ItemsSource="{Binding Path=cuCodeInfo.CitationTypes}"
Text="{Binding cit_type}"
IsEditable="true"
IsReadOnly="false"
**SelectedItem="{Binding SelectedItem}"**>
于 2013-08-13T03:02:36.103 回答