将wpf文本框绑定到listBox的selectedItem

时间:2013-12-14 18:42:03

标签: c# wpf binding observablecollection

我有两个班级

Class A
{
     public int something { get; set; }
     public B classB = new B();
}


Class B
{
     public int anotherThing { get; set; }
}

我有来自A组的ObservableCollection

public ObservableCollection<A> listOfClasses = new ObservableCollection<A>();

现在,我有一个绑定到listOfClasses的列表框

                    <ListBox x:Name="justAList" SelectionMode="Extended">
                        <ListBox.ItemContainerStyle>
                            <Style TargetType="{x:Type ListBoxItem}">
                                <Setter Property="Content" Value="{Binding Path=something}"></Setter>
                            </Style>
                        </ListBox.ItemContainerStyle>
                    </ListBox>

当然还有绑定。

justAList.ItemsSource = listOfClasses ;

到目前为止一切正常。我能够看到列表及其项目(我正在使用其他方法将项目添加到列表中)。 我的问题是,我想要另一个文本框并将其绑定到B类中的anotherThing int。如何才能完成?

1 个答案:

答案 0 :(得分:1)

首先,如果您需要绑定支持,则需要make class B a property的实例:

private B classB = new B();
public B ClassB
{
   get
   {
      return classB;
   }
   set
   {
      classB = value;
   }
}

现在您可以像这样绑定到TextBox:

<TextBox Text="{Binding ClassB.anotherThing}"/>

确保将TextBox DataContext设置为ClassA的某个实例。

<强>更新

如评论中所述,您希望将TextBox TextSelectedItem instance绑定,这可以通过以下方式实现:

<TextBox Text="{Binding ElementName=justAList, 
                        Path=SelectedItem.ClassB.anotherThing}"/>