繁体   English   中英

将WPF文本框绑定到listBox的selectedItem

[英]Bind wpf textbox to selectedItem of listBox

我有两节课

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。如何实现?

首先,你需要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}"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM