2012-08-22 92 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屬性的對象。