WPF组合框绑定文本

3
也许这是一个简单的任务,但我找不到解决方案。我有一个连接到数据库的下拉框。我想在弹出菜单中显示“男”和“女”,而不是显示“ProductLookup”的内容。
谢谢。
<ComboBox Height="23" Name="ComboBox2" Width="120"  IsEditable="False"
                      ItemsSource="{Binding Source={StaticResource ProductLookup}}"
                      SelectedValue="{Binding Path=ProductID}" 
                      SelectedValuePath="ProductID" 
                      DisplayMemberPath="Name"/>
2个回答

3

编写一个转换器(Converter),它接受一个你的"产品(Product)"对象...

查看其中的性别相关数据,或进行性别判断逻辑,然后返回性别字符串"男(male)"或"女(female)"。

然后在 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来包装您的Product对象,该对象具有指示Product“性别”的特定属性...然后创建这些对象的集合以设置在您的ComboBox中...然后您可以使用DisplayMemberPath指向该属性。


0
请查看this答案,这是一种将您的值包装以进行良好绑定和在WPF中显示的方法。
Item类可以修改以支持Code属性的对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接