尝试在文本框 WPF 上显示列表视图上的内容

发布于 2024-12-09 02:38:46 字数 6181 浏览 0 评论 0原文

我有一个带有列表视图的 WPF,其中填充了来自数据库的名称。列表视图(gridview)上有 3 列(姓名、年龄、年级)。我想做的是,当我在列表视图上选择一个人时,我希望他们的信息显示在文本框中。我不确定通过代码还是 XAML 是否更好,但我无法弄清楚。任何帮助表示赞赏。

这是我所拥有的:

          namespace Camp_
 {
/// <summary>
/// Interaction logic for CampersPage.xaml
/// </summary>
public partial class CampersPage : Page
{
    MainWindow _parentForm;

    public CampersPage(MainWindow parent)
    {
        _parentForm = parent;
        InitializeComponent();


        for (int i = 0; i < _parentForm.allCampers.Count; i++)
        {


            listViewCampers.Items.Add(new { Name = "" + _parentForm.allCampers[i].getName(), Age = "" + _parentForm.allCampers[i].getAge(), Grade = "" + _parentForm.allCampers[i].getGrade() });

        }
    }


        private void listViewCampers_SelectionChanged(object sender, SelectionChangedEventArgs e)

    {
        for (int i = 0; i < _parentForm.allCampers.Count; i++)
        {


                //  txtName.Text = listViewCampers.SelectedItem.Col1.toString();
            txtName.Text = "" + _parentForm.allCampers[i].getName();
                txtAge.Text = "" + _parentForm.allCampers[i].getAge();
                txtGrade.Text = "" + _parentForm.allCampers[i].getGrade();


        }

        }
    }
  }


        // _parentForm.ListToText();
           // for (int i = 0; i < _parentForm.testClass.g1.members.Count; i++)
        /*
            {  
                if (listViewCampers.SelectedItem == _parentForm.testClass.g1.members[i].getName())
                { 
                    txtName.Text = _parentForm.testClass.g1.members[i].getName();
                    txtAge.Text = "" + _parentForm.testClass.g1.members[i].getAge();
                    txtGrade.Text = "" + _parentForm.testClass.g1.members[i].getGrade();
                    txtRequest1.Text = "None";
                    txtRequest2.Text = "None";
                    txtRequest3.Text = "None";

                    Camper[] x = _parentForm.testClass.g1.members[i].getRequests();

                    if (x[0] != null && x[1] != null && x[2] != null)
                    {
                        txtRequest1.Text = "" + x[0].getName();
                        txtRequest2.Text = "" + x[1].getName();
                        txtRequest3.Text = "" + x[2].getName();
            } } } 
    */

       //txtName.Text = listViewCampers.SelectedItem.Col1.toString();
        //txtAge.Text = "" + _parentForm.allCampers[i].getAge();
        //txtGrade.Text = "" + _parentForm.allCampers[i].getGrade();

这是 XAML:

     <Page x:Class="Camp_.CampersPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  mc:Ignorable="d" 
  d:DesignHeight="300" d:DesignWidth="570"
Title="Campers Page" ShowsNavigationUI="False" xmlns:my="clr-namespace:Camp_"  >

<Grid Name="camperGrid">
    <Grid.Background>
        <RadialGradientBrush>
            <GradientStop Color="#FFC3D6F5" Offset="0" />
            <GradientStop Color="#FFEFF5FF" Offset="1" />
        </RadialGradientBrush>
    </Grid.Background>





        <ListView HorizontalAlignment="Left" Margin="10,10,0,40" Name="listViewCampers" Width="200" SelectionChanged="listViewCampers_SelectionChanged">

            <ListView.View>
                <GridView>



                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="100"  />
                    <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="40" />
                    <GridViewColumn Header="Grade" DisplayMemberBinding="{Binding Grade}" Width="40" />

                </GridView>
            </ListView.View>
        </ListView>
        <Grid Height="Auto" HorizontalAlignment="Stretch" Margin="209,12,0,0" Name="infoGrid" VerticalAlignment="Stretch">
            <Grid.RowDefinitions>
                <RowDefinition Height="134*" />
                <RowDefinition Height="154*" />
            </Grid.RowDefinitions>
            <Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="23,24,0,0" Name="lblName" VerticalAlignment="Top" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="23,46,0,0" Name="txtName" VerticalAlignment="Top" Width="120" AcceptsReturn="True" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="23,103,0,0" Name="txtAge" VerticalAlignment="Top" Width="120" />
            <Label Content="Age" Height="28" HorizontalAlignment="Left" Margin="23,75,0,0" Name="lblAge" VerticalAlignment="Top" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="23,27,0,0" Name="txtGrade" VerticalAlignment="Top" Width="120" Grid.Row="1" />
            <Label Content="Grade" Height="28" HorizontalAlignment="Left" Margin="23,0,0,0" Name="lblGrade" VerticalAlignment="Top" Grid.Row="1" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="180,46,0,0" Name="txtRequest1" VerticalAlignment="Top" Width="120" />
            <Label Content="Roommate Request #1" Height="28" HorizontalAlignment="Left" Margin="180,24,0,0" Name="lblRequest" VerticalAlignment="Top" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="180,103,0,0" Name="txtRequest2" VerticalAlignment="Top" Width="120" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="180,27,0,0" Name="txtRequest3" VerticalAlignment="Top" Width="120" Grid.Row="1" />
            <Label Content="Roommate Request #2" Height="28" HorizontalAlignment="Left" Margin="180,75,0,0" Name="label1" VerticalAlignment="Top" />
            <Label Content="Roommate Request #3" Height="28" HorizontalAlignment="Left" Margin="180,0,0,0" Name="label2" VerticalAlignment="Top" Grid.Row="1" />
        </Grid>

</Grid>

I have a WPF with a listview filled with names that are coming from a database. On the listview(gridview) are 3 coloumns (Name, Age, Grade). What I'm trying to do is when I select a person on the listview I want their information to display in textboxes. I'm not sure if its better to do it through code or XAML, but I can't figure it out. Any help is appreciated.

Heres what I have:

          namespace Camp_
 {
/// <summary>
/// Interaction logic for CampersPage.xaml
/// </summary>
public partial class CampersPage : Page
{
    MainWindow _parentForm;

    public CampersPage(MainWindow parent)
    {
        _parentForm = parent;
        InitializeComponent();


        for (int i = 0; i < _parentForm.allCampers.Count; i++)
        {


            listViewCampers.Items.Add(new { Name = "" + _parentForm.allCampers[i].getName(), Age = "" + _parentForm.allCampers[i].getAge(), Grade = "" + _parentForm.allCampers[i].getGrade() });

        }
    }


        private void listViewCampers_SelectionChanged(object sender, SelectionChangedEventArgs e)

    {
        for (int i = 0; i < _parentForm.allCampers.Count; i++)
        {


                //  txtName.Text = listViewCampers.SelectedItem.Col1.toString();
            txtName.Text = "" + _parentForm.allCampers[i].getName();
                txtAge.Text = "" + _parentForm.allCampers[i].getAge();
                txtGrade.Text = "" + _parentForm.allCampers[i].getGrade();


        }

        }
    }
  }


        // _parentForm.ListToText();
           // for (int i = 0; i < _parentForm.testClass.g1.members.Count; i++)
        /*
            {  
                if (listViewCampers.SelectedItem == _parentForm.testClass.g1.members[i].getName())
                { 
                    txtName.Text = _parentForm.testClass.g1.members[i].getName();
                    txtAge.Text = "" + _parentForm.testClass.g1.members[i].getAge();
                    txtGrade.Text = "" + _parentForm.testClass.g1.members[i].getGrade();
                    txtRequest1.Text = "None";
                    txtRequest2.Text = "None";
                    txtRequest3.Text = "None";

                    Camper[] x = _parentForm.testClass.g1.members[i].getRequests();

                    if (x[0] != null && x[1] != null && x[2] != null)
                    {
                        txtRequest1.Text = "" + x[0].getName();
                        txtRequest2.Text = "" + x[1].getName();
                        txtRequest3.Text = "" + x[2].getName();
            } } } 
    */

       //txtName.Text = listViewCampers.SelectedItem.Col1.toString();
        //txtAge.Text = "" + _parentForm.allCampers[i].getAge();
        //txtGrade.Text = "" + _parentForm.allCampers[i].getGrade();

Heres the XAML:

     <Page x:Class="Camp_.CampersPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  mc:Ignorable="d" 
  d:DesignHeight="300" d:DesignWidth="570"
Title="Campers Page" ShowsNavigationUI="False" xmlns:my="clr-namespace:Camp_"  >

<Grid Name="camperGrid">
    <Grid.Background>
        <RadialGradientBrush>
            <GradientStop Color="#FFC3D6F5" Offset="0" />
            <GradientStop Color="#FFEFF5FF" Offset="1" />
        </RadialGradientBrush>
    </Grid.Background>





        <ListView HorizontalAlignment="Left" Margin="10,10,0,40" Name="listViewCampers" Width="200" SelectionChanged="listViewCampers_SelectionChanged">

            <ListView.View>
                <GridView>



                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="100"  />
                    <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="40" />
                    <GridViewColumn Header="Grade" DisplayMemberBinding="{Binding Grade}" Width="40" />

                </GridView>
            </ListView.View>
        </ListView>
        <Grid Height="Auto" HorizontalAlignment="Stretch" Margin="209,12,0,0" Name="infoGrid" VerticalAlignment="Stretch">
            <Grid.RowDefinitions>
                <RowDefinition Height="134*" />
                <RowDefinition Height="154*" />
            </Grid.RowDefinitions>
            <Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="23,24,0,0" Name="lblName" VerticalAlignment="Top" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="23,46,0,0" Name="txtName" VerticalAlignment="Top" Width="120" AcceptsReturn="True" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="23,103,0,0" Name="txtAge" VerticalAlignment="Top" Width="120" />
            <Label Content="Age" Height="28" HorizontalAlignment="Left" Margin="23,75,0,0" Name="lblAge" VerticalAlignment="Top" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="23,27,0,0" Name="txtGrade" VerticalAlignment="Top" Width="120" Grid.Row="1" />
            <Label Content="Grade" Height="28" HorizontalAlignment="Left" Margin="23,0,0,0" Name="lblGrade" VerticalAlignment="Top" Grid.Row="1" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="180,46,0,0" Name="txtRequest1" VerticalAlignment="Top" Width="120" />
            <Label Content="Roommate Request #1" Height="28" HorizontalAlignment="Left" Margin="180,24,0,0" Name="lblRequest" VerticalAlignment="Top" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="180,103,0,0" Name="txtRequest2" VerticalAlignment="Top" Width="120" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="180,27,0,0" Name="txtRequest3" VerticalAlignment="Top" Width="120" Grid.Row="1" />
            <Label Content="Roommate Request #2" Height="28" HorizontalAlignment="Left" Margin="180,75,0,0" Name="label1" VerticalAlignment="Top" />
            <Label Content="Roommate Request #3" Height="28" HorizontalAlignment="Left" Margin="180,0,0,0" Name="label2" VerticalAlignment="Top" Grid.Row="1" />
        </Grid>

</Grid>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等待我真够勒 2024-12-16 02:38:46

您应该看看使用 MVVM 设计模式 用于更好地分离关注点,这将使测试和重用您的代码库变得更加容易。

在这种情况下,您可以通过将周围元素(例如围绕文本框的 Grid)的 DataContext 绑定到 XAML 中以声明方式绑定文本框的值。 ListViewSelectedItem

You should have a look at using the MVVM design pattern for a greater separation of concerns, which is going to make testing and reusing your codebase much easier.

In this instance, you can bind the values of the text boxes declaratively in XAML by binding the DataContext of a surrounding element (e.g. a Grid that surrounds your text boxes) to the SelectedItem of the ListView.

街角迷惘 2024-12-16 02:38:46

正如已经提到的,带有数据绑定的 MVVM 是最佳选择。

这是一个小型的 MVVM 类型工作示例,可能会为您指明正确的方向。

查看第三段中链接的视频,以帮助您完成:) MVVM - Jason Dollinger

以及有关更多有用的 WPF 信息,请查看 WPFTutorial.net

MainWindow.xaml

<Window x:Class="WpfBindingSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:models="clr-namespace:WpfBindingSample.Models"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <ListBox Grid.Column="0" SelectedValue="{Binding Path=SelectedPerson, Mode=TwoWay}" ItemsSource="{Binding People}">
            <ListBox.Resources>
                <DataTemplate DataType="{x:Type models:Person}" >
                    <StackPanel>
                        <TextBlock Text="{Binding FirstName}" />
                        <TextBlock Text="{Binding LastName}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.Resources>
        </ListBox>
        <StackPanel Grid.Column="1" DataContext="{Binding SelectedPerson}">
            <TextBlock Text="{Binding FirstName}" />
            <TextBlock Text="{Binding LastName}" />
        </StackPanel>
    </Grid>
</Window>

Person.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace WpfBindingSample.Models
{
    public class Person : DependencyObject
    {


        public string FirstName
        {
            get { return (string)GetValue(FirstNameProperty); }
            set { SetValue(FirstNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for FirstName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FirstNameProperty =
            DependencyProperty.Register("FirstName", typeof(string), typeof(Person), new UIPropertyMetadata(""));



        public string LastName
        {
            get { return (string)GetValue(LastNameProperty); }
            set { SetValue(LastNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for LastName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty LastNameProperty =
            DependencyProperty.Register("LastName", typeof(string), typeof(Person), new UIPropertyMetadata(""));



    }
}

MainWindowViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Collections.ObjectModel;
using WpfBindingSample.Models;

namespace WpfBindingSample
{
    public class MainWindowViewModel : DependencyObject
    {
        public MainWindowViewModel()
        {
            People = new System.Collections.ObjectModel.ObservableCollection<Person>();
        }

        public Person SelectedPerson
        {
            get { return (Person)GetValue(SelectedPersonProperty); }
            set { SetValue(SelectedPersonProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedPerson.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedPersonProperty =
            DependencyProperty.Register("SelectedPerson", typeof(Person), typeof(MainWindowViewModel), new UIPropertyMetadata(null));

        public ObservableCollection<Person> People { get; set; }
    }
}

As already mentioned MVVM with Databinding is the way to go.

Here is a small working MVVM type sample that may point you in the right direction.

Check out the video linked to in the 3rd paragraph to help you along :) MVVM - Jason Dollinger

And for more helpful WPF information check out WPFTutorial.net

MainWindow.xaml

<Window x:Class="WpfBindingSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:models="clr-namespace:WpfBindingSample.Models"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <ListBox Grid.Column="0" SelectedValue="{Binding Path=SelectedPerson, Mode=TwoWay}" ItemsSource="{Binding People}">
            <ListBox.Resources>
                <DataTemplate DataType="{x:Type models:Person}" >
                    <StackPanel>
                        <TextBlock Text="{Binding FirstName}" />
                        <TextBlock Text="{Binding LastName}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.Resources>
        </ListBox>
        <StackPanel Grid.Column="1" DataContext="{Binding SelectedPerson}">
            <TextBlock Text="{Binding FirstName}" />
            <TextBlock Text="{Binding LastName}" />
        </StackPanel>
    </Grid>
</Window>

Person.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace WpfBindingSample.Models
{
    public class Person : DependencyObject
    {


        public string FirstName
        {
            get { return (string)GetValue(FirstNameProperty); }
            set { SetValue(FirstNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for FirstName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FirstNameProperty =
            DependencyProperty.Register("FirstName", typeof(string), typeof(Person), new UIPropertyMetadata(""));



        public string LastName
        {
            get { return (string)GetValue(LastNameProperty); }
            set { SetValue(LastNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for LastName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty LastNameProperty =
            DependencyProperty.Register("LastName", typeof(string), typeof(Person), new UIPropertyMetadata(""));



    }
}

MainWindowViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Collections.ObjectModel;
using WpfBindingSample.Models;

namespace WpfBindingSample
{
    public class MainWindowViewModel : DependencyObject
    {
        public MainWindowViewModel()
        {
            People = new System.Collections.ObjectModel.ObservableCollection<Person>();
        }

        public Person SelectedPerson
        {
            get { return (Person)GetValue(SelectedPersonProperty); }
            set { SetValue(SelectedPersonProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedPerson.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedPersonProperty =
            DependencyProperty.Register("SelectedPerson", typeof(Person), typeof(MainWindowViewModel), new UIPropertyMetadata(null));

        public ObservableCollection<Person> People { get; set; }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文