如何将文本框文本绑定到“当前”集合项

时间:2014-11-22 04:41:25

标签: wpf data-binding datagrid

我是WPF的新手并且一整天都试图解决这个问题:

我有一个包含六个公共属性的列表(阅读有关仅绑定到公共属性的wpf)。

在我的主窗口中,我有两个控件;一个包含三列和三个文本框的数据网格。我希望将三个datagrid列数据绑定到我的List的三个属性,并将我的List的其余三个属性数据绑定到文本框(每个文本框一个属性)。 datagrid数据绑定工作正常:myDataGrid.ItemsSource = myList; //specific column binding is in xaml as expected eg Binding="{Binding Title, Mode=TwoWay}"

麻烦在于文本框。我打算让文本框在底层列表中显示“当前项目”,这意味着当用户选择不同的数据网格行时,文本框应该更改以显示“当前所选列表项”的数据绑定属性的值。简单地绑定像这样的texbox就不起作用了:

Text="{Binding SomePropertyName}"

我已经阅读了有关使用CollectionViewSource的信息,以便在xaml绑定中使用正斜杠来促进“当前项目”指针,但是没有运气,即

<Textbox Text="{Binding Path=/someProperty}"

我还读过关于使用'elementname'绑定将数据绑定到datagrid / listview项目的人,但这不是我所追求的。我认为应该很容易,至少在winforms中是这样的!

提前致谢。

1 个答案:

答案 0 :(得分:1)

这很容易,但有一点需要注意。默认情况下,您可以在DataGrid中选择多行,在这种情况下,文本框中只会显示一个值。您可以通过在数据网格上设置SelectionMode="Single"来更改此设置。

<StackPanel>
    <DataGrid x:Name="PersonsGrid" ItemsSource="{Binding Persons}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="First name" Binding="{Binding FirstName}" />
            <DataGridTextColumn Header="Last name" Binding="{Binding LastName}" />
            <DataGridTextColumn Header="Age" Binding="{Binding Age}" />
        </DataGrid.Columns>
    </DataGrid>

    <TextBox Text="{Binding SelectedItem.Address, ElementName=PersonsGrid}" />
</StackPanel>

这是有效的,因为我的示例中SelectedItem的基础类型为Person

相关问题