【问题标题】:Binding Text Property of child element of ComboBoxItemComboBoxItem 子元素的绑定文本属性
【发布时间】:2012-01-09 19:06:35
【问题描述】:

我有一个 WPF 组合框,其中包含带有图像和名字的静态人员列表。我正在尝试将选定的 FirstName 绑定到数据库表。我现在这样做的方式(显然是错误的)我只是绑定对象并因此编写:

System.Windows.Controls.ComboBoxItem

到我的数据库表。

如何从 TextBlock.Text 属性中选择 ComboBoxItem 绑定 FirstName?有没有办法纯粹在 WPF 中做到这一点?

      <ComboBox Text="{Binding Path=FirstName}">
        <ComboBoxItem>
            <StackPanel Orientation="Horizontal" >
                <Image Source="/Images/Alice.png" />
                <TextBlock Text="Alice" />
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem>
            <StackPanel Orientation="Horizontal">
                <Image Source="/Images/Bob.png" />
                <TextBlock Text="Bob" />
            </StackPanel>
        </ComboBoxItem>
    </ComboBox>  

我正在通过按钮单击事件保存对 db 表的更改

    private void SaveAndClose_Click(object sender, RoutedEventArgs e)
    {
        bindingView = (BindingListCollectionView)myCollection.View;
        bindingView.CommitEdit();
        db.SubmitChanges();
    }

【问题讨论】:

  • 您能否显示用于处理所选项目更改的代码?您将必须有一些代码隐藏才能写入数据库,因为 WPF 仅用作表示层。
  • 我没有使用选中的项目更改事件。我应该吗?

标签: wpf binding combobox


【解决方案1】:

您应该使用数据模板,而不是对组合框项进行硬编码。然后,您应该使用 SelectedValuePath 根据项目中的 FirstName 属性选择值。然后你可以绑定到文本框。

如果要直接绑定到 xaml 中的文本框,则需要命名元素 (x:Name="myTextBox")。然后,像这样绑定组合框的 SelectedValue:SelectedValue="{Binding ElementName="myTextBox", Path="Text"}"。

总的来说,我认为将组合框绑定到文本框并不是一个好主意。

【讨论】:

    猜你喜欢
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2012-04-29
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多