[英]WPF ComboBox Databinding from Code Behind
In the code behind I have a private List<string> _materials
I would like to display in a combox. 在后面的代码中,我有一个private List<string> _materials
我想在private List<string> _materials
中显示。
I need to create the data binding in Parts from the Code behind, since I'm filling _materials
through a background worker: 我需要通过后面的代码在Part中创建数据绑定,因为我是通过后台工作人员填充_materials
:
public partial class MainWindow : Window
{
private List<string> _materials;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.DoWork += worker_DoWork;
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
_materials = DataSupplier.GetMaterials();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Do Databinding Here
wpMaterial.DataContext = _materials;
cmbMaterial.ItemsSource = _materials;
}
XAML Looks like this: XAML看起来像这样:
<WrapPanel x:Name="wpMaterial" >
<Label Content="Material: " FontStyle="Italic" FontFamily="Arial" Foreground="Black" Background="{x:Null}" Width="100" />
<ComboBox Name="cmbMaterial">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="Hi" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</WrapPanel>
"Hi" is displayed for every entry i have in my _materials
list, but the actual Name is not displayed. 我在_materials
列表中为每个条目显示“ Hi”,但不显示实际名称。 So What do I need to put in Text="{Binding ???}"
to get my string content displayed? 那么,我需要输入Text="{Binding ???}"
来显示我的字符串内容吗?
Because _materials
is a list of string
it means each item will be of string
type so you want to bind to current DataContext
of ComboBoxItem
. 因为_materials
是一个string
列表,所以它意味着每个项目都是string
类型,因此您想绑定到ComboBoxItem
当前DataContext
。
You can either use {Binding}
or {Binding Path=.}
您可以使用{Binding}
或{Binding Path=.}
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" />
<TextBlock Text="Hi" />
</StackPanel>
</DataTemplate>
Optionally, a period (.) path can be used to bind to the current source. (可选)可以使用句点(。)路径绑定到当前源。 For example, Text="{Binding}" is equivalent to Text="{Binding Path=.}". 例如,Text =“ {Binding}”等效于Text =“ {Binding Path =。}”。
由于您绑定的ItemsSource只是一个字符串集合,因此只需要指定Text="{Binding}"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.