2012-08-22 94 views
2

也许一个简单的任务,但我找不到解决方案。我有一个连接到数据库的组合框。我不想显示ProductLookup的内容,我只想在弹出菜单中显示“男性”和“女性”等字样。WPF Combobox绑定文本

谢谢

<ComboBox Height="23" Name="ComboBox2" Width="120" IsEditable="False" 
         ItemsSource="{Binding Source={StaticResource ProductLookup}}" 
         SelectedValue="{Binding Path=ProductID}" 
         SelectedValuePath="ProductID" 
         DisplayMemberPath="Name"/> 

回答

3

Converter是把你的“产品”对象之一....看着里面的性别有关的数据,或者做性别判断逻辑,然后返回性别字符串,“男”或“女”。

然后用它在你的XAML设置TextBlock

<StackPanel Height="197" HorizontalAlignment="Left" Margin="300,6,0,0" Name="StackPanel5" VerticalAlignment="Top" Width="285" 
          DataContext="{Binding Source={StaticResource DetailViewPagos}}"> 
    <StackPanel.Resources> 
     <local:ProductToGenderConverter x:Key="prodtogenderconv"/> 
    </StackPanel.Resources> 

    <ComboBox Height="23" Name="ComboBox2" Width="120" IsEditable="False" 
     ItemsSource="{Binding Source={StaticResource ProductLookup}}"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Converter={StaticResource prodtogenderconv}}" /> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
    </ComboBox> 

public class ProductToGenderConverter : IValueConverter { 

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { 

     MyProduct prod = value as MyProduct; 

     if (prod is for a male) // Pseudocode for condition 
      return "male"; 

     if (prod is for a female) // Pseudocode for condition 
      return "female"; 

     return null or ""; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { 
     throw new NotImplementedException(); 
    } 
} 

或者,您也可以提供一个ViewModel它包装你的产品对象,它具有指示特定属性“性别“,然后创建这些对象的集合,以便在ComboBox中进行设置...然后您可以使用DisplayMemberPath指向该属性。

0

请参阅this答案,这是一种包装您的值的方式,以便在WPF中进行很好的绑定和显示。

Item类可以修改为支持Code属性的对象。