C# 如何在 WPF ComboBox 中使用 MultiBinding

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2197775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:18:57  来源:igfitidea点击:

How to use MultiBinding in a WPF ComboBox

c#wpfdata-bindingxamlivalueconverter

提问by Mike B

This is driving me NUTS!!!

这让我发疯了!!!

I have a ComboBoxused to filter a query by employee which works fine but only displays the employees first name. I want to use a MultiValueConverterto display the employees full name (This would be less urgent if we did not have 2 Mikes and 2 Daves)

我有一个ComboBox用于按员工过滤查询的方法,它工作正常,但只显示员工的名字。我想使用 aMultiValueConverter来显示员工的全名(如果我们没有 2 Mikes 和 2 Daves,这将不那么紧迫)

Below is my working code and the IMultiValueConverterClass (With unnecessary formatting trimmed out for brevity). I have tried everything I can think of to get the MultiConverter to work but I have had no luck.

下面是我的工作代码和IMultiValueConverter类(为简洁起见,删除了不必要的格式)。我已经尝试了所有我能想到的方法来让 MultiConverter 工作,但我没有运气。

<ComboBox ItemsSource="{Binding Path=EmployeesFilter}" 
                       DisplayMemberPath="EmpFirstName"
                       SelectedValue="{Binding Path=EmployeeToShow, Mode=TwoWay}"/>

The ViewModel Properties it is bound to:

它绑定到的 ViewModel 属性:

// This collection is used to populate the Employee Filter ComboBox
private ObservableCollection<Employee> employeesFilter;
public ObservableCollection<Employee> EmployeesFilter
{
    get {
            return employeesFilter;
        }
    set {
        if (employeesFilter != value)
        {
            employeesFilter = value;
            OnPropertyChanged("EmployeesFilter");
        }
    }
}

// This property is TwoWay bound to the EmployeeFilters SelectedValue
private Employee employeeToShow;
public Employee EmployeeToShow
{
    get {
            return employeeToShow;
        }
    set {
        if (employeeToShow != value)
        {
            employeeToShow = value;
            OnPropertyChanged("EmployeeToShow");
            QueryIssues(); // Requery with new employee filter
        }
    }
}

The IMultiValueConverter:

IMul​​tiValueConverter:

class StringsToFullNameMultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, 
                          Type targetType, 
                          object parameter, 
                          System.Globalization.CultureInfo culture)
    {
        // I added this because I kept getting DependecyProperty.UnsetValue 
        // Passed in as the program initializes
        if (values[0] as string != null)
        {
            string firstName = (string)values[0];
            string lastName = (string)values[1];
            string fullName = firstName + " " + lastName;
            return fullName;
        }
        return null;
    }

    public object[] ConvertBack(object value, 
                                Type[] targetTypes, 
                                object parameter, 
                                System.Globalization.CultureInfo culture)
    {
        return null; 
    }
}

I tried a lot of different things but basically am using the following in the ComboBox

我尝试了很多不同的东西,但基本上是在 ComboBox 中使用以下内容

<ComboBox.SelectedValue>
     <MultiBinding Converter="{StaticResource StringsToFullNameMultiConverter}" 
                   Mode="OneWay" > 
           <Binding Path="EmpFirstName" />
           <Binding Path="EmpLastName"/>
     </MultiBinding>
</ComboBox.SelectedValue>

As it stands now the converter is called when the program initializes with the values set to DependencyProperty.UnsetValue. after that it is never called again, even when you select a name from the box. The names are still displayed as a first name.

就目前而言,当程序使用设置为 的值进行初始化时,将调用转换器DependencyProperty.UnsetValue。之后,即使您从框中选择一个名称,也不会再次调用它。名称仍显示为名字。

Thanks for any help or pointers to good tutorials/samples you can provide. All the ones I keep finding on the web are for textboxes and I can use them just fine all day.

感谢您提供任何帮助或指向好的教程/示例的指针。我在网上找到的所有文本框都是用于文本框的,我可以整天使用它们。

采纳答案by Josh

You're close! What you want to do though is ComboBox.ItemTemplate, not SelectedValue. Prepare for some XAML hell.

你很接近!你想要做的是ComboBox.ItemTemplate,而不是SelectedValue。为一些 XAML 地狱做好准备。

<ComboBox.ItemTemplate>
    <DataTemplate>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding Converter="{StaticResource StringsToFillNameMultiConverter}">
                    <Binding Path="EmpFirstName" />
                    <Binding Path="EmpLastName" />
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </DataTemplate>
</ComboBox.ItemTemplate>

Also, if I recall correctly, you don't need to create your own converter if you're just formatting strings. I think you can do the following (someone please correct me if I'm wrong.)

另外,如果我没记错的话,如果您只是格式化字符串,则不需要创建自己的转换器。我认为您可以执行以下操作(如果我错了,请有人纠正我。)

<!-- "Last, First" -->
<MultiBinding StringFormat="{}{1}, {0}">
    <Binding Path="EmpFirstName" />
    <Binding Path="EmpLastName" />
</MultiBinding>

回答by Ian Ringrose

You may be better of using a data template for the items, so you have complete control over how each person is displayed in the dropdown list.

您最好为项目使用数据模板,这样您就可以完全控制每个人在下拉列表中的显示方式。

The type convert is OK provided you don't have a need to control the formatting of the different fields.

如果您不需要控制不同字段的格式,则类型转换是可以的。

回答by dba

I ended up by addig a Readonly Property to my Class and use Displaymemberpath in the Combobox

我最终将只读属性添加到我的类并在组合框中使用 Displaymemberpath

public class MyEmployee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DisplayName {
    get { return FirstName + " " + LastName; }
        }
}

Could something like this work for your situation...? BR, Daniel

这样的事情可以为您的情况工作......?BR,丹尼尔