数据绑定控件到ComboBoxItem的属性

时间:2016-10-26 12:02:18

标签: c# wpf xaml data-binding combobox

我正在尝试使用ComboBox创建一个WPF窗口,您可以使用该窗口选择一个项目,然后使用下面的TextBoxes编辑当前所选项目的属性,例如{{1} }和Name

如何使用数据绑定执行此操作,即。将名称Age绑定到TextBox中当前所选项目的Name属性?

我的XAML

ComboBox

我的代码背后是

<Window x:Class="BindingTest001.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        >
    <Grid>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="10,75,0,0" TextWrapping="Wrap" Text="{Binding Path=CURR.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="497"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="10,103,0,0" TextWrapping="Wrap" Text="{Binding Path=CURR.Age, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
        <ComboBox ItemsSource="{Binding Path=MO}" SelectedValue="{Binding Path=CURR, Mode=TwoWay}" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="497" Name="MyComboBox"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="322,181,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>
</Window>

但数据绑定仅适用于public partial class MainWindow : Window { ObservableCollection<myObj> mo; public MainWindow() { InitializeComponent(); mo = new ObservableCollection<myObj>(); mo.Add(new myObj("Test1", 2)); var ct = new MainWindowDatacontext(this); this.DataContext = ct; this.MyComboBox.SelectedIndex = 0; } private class MainWindowDatacontext : INotifyPropertyChanged { MainWindow parent; myObj curr; public MainWindowDatacontext(MainWindow mainWindow) { this.parent = mainWindow; } public ObservableCollection<myObj> MO { get { return parent.mo; } } public myObj CURR { get { return curr; } set { this.curr = value; } } public event PropertyChangedEventHandler PropertyChanged; public void executePropertyChanged(string s) { if(PropertyChanged!=null) { PropertyChanged(this.parent, new PropertyChangedEventArgs(s)); } } } private void Button_Click(object sender, RoutedEventArgs e) { mo.Add(new myObj("Test2", 10)); } } - ComboBox永远不会绑定任何内容。

TextBoxes非常简单:

myObj

2 个答案:

答案 0 :(得分:1)

因为要绑定到应用程序中另一个元素的属性,所以应该使用Ruport属性。所以改变你的TextBox Binding就像这样:

Text="{Binding SelectedItem.Name, ElementName=MyComboBox, 
               Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
Text="{Binding SelectedItem.Age, ElementName=MyComboBox,
               Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

答案 1 :(得分:0)

您在ComboBox中使用SelectedValue而不是SelectedItem

前者用于在ComboBox的ItemsSource中从对象中选择一个属性而不是对象本身。它与SelectedValuePath一起使用。

如果您想要编辑所选项目的多个属性,则需要使用SelectedItem