我想将我的类(class)列表绑定(bind)到 WPF 中的 CombpBox。我觉得应该很简单。
我尝试了代码,但它不起作用:
public MainWindow()
{
InitializeComponent();
List<SimpleClass> ListData = new List<SimpleClass>();
ListData.Add(new SimpleClass { Id = "1", Value = "One" });
ListData.Add(new SimpleClass { Id = "2", Value = "Two" });
ListData.Add(new SimpleClass { Id = "3", Value = "Three" });
ListData.Add(new SimpleClass { Id = "4", Value = "Four" });
ListData.Add(new SimpleClass { Id = "5", Value = "Five" });
comboBox1.DataContext = ListData;
comboBox1.DisplayMemberPath = "{Binding Path=Value}";
comboBox1.SelectedValuePath = "{Binding Path=Id}";
}
}
public class SimpleClass
{
public string Id;
public string Value;
}
XAML如下
<ComboBox Height="23" HorizontalAlignment="Left" Margin="221,107,0,0" Name="comboBox1" ItemsSource="{Binding}" VerticalAlignment="Top" Width="120" />
我做错了什么?
最佳答案
应该是
comboBox1.DisplayMemberPath = "Value";
comboBox1.SelectedValuePath = "Id";
在后面的代码中,您不能通过设置字符串来分配绑定(bind),这有点复杂。在这种情况下,DisplayMemberPath
和 SelectedValuePath
只需要属性名称,而不需要绑定(bind)。
关于c# - 将简单的 List<myClass> 绑定(bind)到 Combobox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9174765/