我有一个组合框,并希望将其ItemsSource绑定到IEnumerable<(string,string)>
。如果我没有设置DisplayMemberPath,那么它将起作用,并在下拉区域显示在项目中调用ToString()
的结果。不过,当我设置DisplayMemberPath="Item1"
它不再显示任何东西。我做了以下示例,其中您可能会看到如果使用经典Tuple
类型,则按预期工作。ValueTuple不支持DisplayMemberPath。组合框,WPF
在调试时,我已经检查到valuetuple的Item1和Item2也是属性。
我的XAML:
<Window x:Class="TupleBindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="MainWindow_OnLoaded"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ComboBox x:Name="TupleCombo" Grid.Row="0" VerticalAlignment="Center"
DisplayMemberPath="Item1" />
<ComboBox x:Name="ValueTupleCombo" Grid.Row="1" VerticalAlignment="Center"
DisplayMemberPath="Item1" />
</Grid>
</Window>
而且我隐藏:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace TupleBindingTest
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private IEnumerable<Tuple<string, string>> GetTupleData()
{
yield return Tuple.Create("displayItem1", "valueItem1");
yield return Tuple.Create("displayItem2", "valueItem2");
yield return Tuple.Create("displayItem3", "valueItem3");
}
private IEnumerable<(string, string)> GetValueTupleData()
{
yield return ("displayItem1", "valueItem1");
yield return ("displayItem2", "valueItem2");
yield return ("displayItem3", "valueItem3");
}
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
TupleCombo.ItemsSource = GetTupleData();
ValueTupleCombo.ItemsSource = GetValueTupleData();
}
}
}
在运行这个样本将正确显示数据在第一组合框,但会什么都不显示在第二位。
为什么会发生这种情况?
这个故事告诉我们,一个'ValueTuple'的项目被暴露领域,而不是性能,和WPF做不支持绑定到字段。 –