C#:使用数据绑定(bind)文本框在 List<Customer> 中导航

标签 c# wpf data-binding textbox

尝试了几个小时后,我对 wpf 复杂的数据绑定(bind)概念感到非常困惑:-/

在几个文本框中显示我的业务对象的属性(例如姓名、街道等)的最简单方法是什么?

目标是:

  • 用户可以浏览记录(下一个,上一个)
  • 双向绑定(bind) - 文本框中的更改也应更改基础属性的值。

我已经想出了如何将框绑定(bind)到属性,但是如何实现到下一条/上一条记录的导航?

提前致谢!

最佳答案

您需要查看 ICollectionView 方法。 这是一个工作示例:

xaml:

<Window.Resources>
    <x:Array x:Key="myPeoples" Type="{x:Type local:Person}">
        <local:Person Name="Bob Marley" Address="123 street" />
        <local:Person Name="Ted Nugent" Address="456 street" />
        <local:Person Name="Ron Paul" Address="789 street" />
    </x:Array>
</Window.Resources>
<DockPanel>
    <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
        <Button x:Name="cmdPrevious" Click="cmdPrevious_Click">Previous</Button>
        <Button x:Name="cmdNext" Click="cmdNext_Click">Next</Button>
    </StackPanel>
    <Grid DockPanel.Dock="Top" DataContext="{StaticResource myPeoples}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBox Grid.Column="0" Text="{Binding Path=Name}" />
        <TextBox Grid.Column="1" Text="{Binding Path=Address}" />
    </Grid>
</DockPanel>

代码隐藏:

private void cmdPrevious_Click(object sender, RoutedEventArgs e)
{
    Person[] peoples = this.FindResource("myPeoples") as Person[];
    System.ComponentModel.ICollectionView collectionView = CollectionViewSource.GetDefaultView(peoples);
    collectionView.MoveCurrentToPrevious();

}

private void cmdNext_Click(object sender, RoutedEventArgs e)
{
    Person[] peoples = this.FindResource("myPeoples") as Person[];
    System.ComponentModel.ICollectionView collectionView = CollectionViewSource.GetDefaultView(peoples);
    collectionView.MoveCurrentToNext();
}

关于C#:使用数据绑定(bind)文本框在 List<Customer> 中导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6319648/

相关文章:

c# - 从 SQL Server 读取 blob 并下载

c# - 当其他数据绑定(bind)有效时,命令绑定(bind)不起作用

c# - 绑定(bind)数据网格列宽

PHP、PDO bindValue - 如何传递逗号分隔的 INT 以用于 'in clause'

wpf - 命名空间中不存在名称 ViewModelLocator

单击“保存”按钮后的 WPF 数据绑定(bind)

c# - 在 C# 中是否有 LZSS 压缩的公共(public)实现或者可以在 C# 中使用?

c# - []上的C#数组初始化

c# - 使用ASIFormDataRequest时如何实现C#服务器端?

c# - 属性绑定(bind)没有响应