【问题标题】:WPF ComboBox Databinding from Code Behind来自代码隐藏的 WPF ComboBox 数据绑定
【发布时间】:2014-12-09 10:44:14
【问题描述】:

在后面的代码中,我有一个 private List<string> _materials 我想在组合框中显示。

我需要在 Parts from the Code behind 中创建数据绑定,因为我正在通过后台工作人员填写 _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 看起来像这样:

<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>

_materials 列表中的每个条目都会显示“Hi”,但不会显示实际名称。那么我需要输入什么Text="{Binding ???}" 才能显示我的字符串内容?

【问题讨论】:

标签: c# wpf xaml data-binding combobox


【解决方案1】:

因为_materialsstring 的列表,这意味着每个项目都将是string 类型,因此您希望绑定到当前DataContextComboBoxItem

您可以使用{Binding}{Binding Path=.}

<DataTemplate>
   <StackPanel Orientation="Horizontal">
      <TextBlock Text="{Binding}" />
      <TextBlock Text="Hi" />
   </StackPanel>
</DataTemplate>

来自MSDN

(可选)句点 (.) 路径可用于绑定到当前源。例如,Text="{Binding}" 等价于 Text="{Binding Path=.}"。

【讨论】:

    【解决方案2】:

    由于你绑定的ItemsSource只是一个字符串集合,你只需要指定Text="{Binding}"即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-17
      • 2021-07-19
      • 2012-07-15
      • 2020-04-23
      • 2018-12-08
      • 2015-12-30
      • 1970-01-01
      相关资源
      最近更新 更多