【问题标题】:How to bind textbox text to 'current' item of collection如何将文本框文本绑定到“当前”集合项
【发布时间】:2015-01-20 08:26:45
【问题描述】:

我是 WPF 新手,整天都在尝试解决这个问题:

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

在我的主窗口中,我有两个控件;具有三列和三个文本框的数据网格。我希望将三个数据网格列数据绑定到我的列表的三个属性,并将我的列表的其余三个属性数据绑定到文本框(每个文本框一个属性)。数据网格数据绑定工作正常: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}"

我还阅读了有关使用“元素名称”绑定将人员数据绑定到数据网格/列表视图项的信息,但这不是我所追求的。我认为应该很容易,至少在 winforms 中是这样!

提前致谢。

【问题讨论】:

    标签: wpf data-binding datagrid


    【解决方案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

    【讨论】:

    • 感谢 Ondrej,非常感谢您的作品。也感谢“SelectionMode”提示。
    • @CoverG 很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 2011-01-14
    • 2011-05-11
    相关资源
    最近更新 更多