将数据从 WPF 窗口发送到 C# 类文件 [英] Send data from a WPF Window to a C# class file

查看:21
本文介绍了将数据从 WPF 窗口发送到 C# 类文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我编写的用于将图像导入数据库的控制台应用程序制作一个简单的 GUI.我有一个 xml 文件,其中包含图像所属的不同研究.我正在用这些研究的名称填充一个列表框.我有一个名为 DirectoryNavigator.cs 的类文件,根据从 ListBox 中选取的名称,该类在该目录中的文件上运行进程.我想知道如何将 ListBox 中的 Selected Value 传递给 DirectoryNavigator.cs 类文件.

I am attempting to make a simple GUI for a console application I wrote for importing images into a database. I have a xml file that contains the different studies that the images belong to. I am populating a ListBox with the name of these studies. I have a class file named DirectoryNavigator.cs, depending on the name picked from the ListBox, this class runs processes on files within that directory. I would like to know how I can pass the Selected Value from the ListBox to the DirectoryNavigator.cs class file.

这是我的 WPF 窗口 .xaml

here is my WPF window .xaml

<Window x:Class="APPIL_Importer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:APPIL_Importer"
        mc:Ignorable="d"
        Background="Gold"
        Title="APPIL Importer" Height="385" Width="600">
    <Grid Style="{StaticResource gridBackground}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto" />
            <RowDefinition />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Grid.Resources>
            <XmlDataProvider x:Key="StudiesDataSource" Source="/Data/StudyData.xml" XPath="Studies" />
            <DataTemplate x:Key="studyName">
                <Label Content="{Binding XPath=@Name}"/>
            </DataTemplate>
        </Grid.Resources>

        <Label Grid.Column="1" Grid.Row="0" Style="{StaticResource homeTitle}">DICOM IMPORTER</Label>

        <Image x:Name="appil_logo" Grid.Column="0" Grid.Row="0" Grid.RowSpan="4" Source="/Images/appil_logo.png"/>

        <Border Grid.Column="1" Grid.Row="0" Style="{StaticResource studyListHeader}" Width="Auto">
            <Label Style="{StaticResource studyListText}">Active Studies</Label>
        </Border>
        <ListBox Name="activeStudiesListBox" Grid.Column="1" Grid.Row="2"
                         ItemsSource="{Binding Source={StaticResource StudiesDataSource}, XPath=Study}"
                         ItemTemplate="{StaticResource studyName}">

        </ListBox>



        <Button Grid.Row="3" Grid.Column="1" Style="{StaticResource buttonStyle}" Click="Go_To_Study_Importer">Select</Button>

    </Grid>
</Window>

这是窗口后面的 xaml.cs 文件.我已经在捕获选定的值并将其传递给另一个窗口,但我不知道如何仅对普通类文件执行此操作

here is the xaml.cs file behind the window. I am already capturing the selected value and passing it to another Window, but I don;t know how to do that to just a plain class file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace APPIL_Importer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Go_To_Study_Importer(object sender, RoutedEventArgs e)
        {
            StudyImporter studyImporter = new StudyImporter(this.activeStudiesListBox.SelectedItem);
            studyImporter.Show();
        }
    }
}

推荐答案

创建继承 INotifyPropertyChanged 的​​ MainViewModel 类,如下所示.

Create MainViewModel class that inherits INotifyPropertyChanged as below.

public class MainViewModel : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

现在您必须将此 ViewModel 绑定到 View 的 DataContext.添加到 MainWindow.xaml 的代码隐藏文件中,如下所示.

Now you have to bind this ViewModel to the DataContext of the View. Add to your code-behind file of the MainWindow.xaml as below.

public MainWindow()
{
    InitializeComponent();

    this.DataContext = new MainViewModel();
}

现在它绑定了 ViewModel(cs) 和 View(XAML).因此,您可以将 Control 的内容带到 cs 文件中.

Now it is bound ViewModel(cs) with View(XAML). Therefore you can bring content of the Control to the cs file.

我会举例说明.

首先为ListBox的每一项添加一个Model.我创建如下是因为我不知道你的项目结构.

First Add a Model for each item of the ListBox. I created as below because I don't know your project structure.

public class ResearchItem
{
    public string Name { get; set; }
}

然后添加到 ViewModel 中,如下所示.这是与 ListBox 内容绑定的实例.

And the add to the ViewModel as below. This is instance for binding with the content of the ListBox.

public class MainViewModel : INotifyPropertyChanged
{
    public ObservableCollection<ResearchItem> Items { get; } = new ObservableCollection<ResearchItem>();

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

然后将其绑定到 XAML 文件中的 ListBox,如下所示.

And then bind it to the ListBox in the XAML file as below.

    <ListBox Width="200" Height="100" ItemsSource="{Binding Items}">
    </ListBox>

这里的项目是集合.ListBox 是显示集合的控件.因此现在 ListBox 将显示 MainViewModel 的 Items.

Here Items is collection. And ListBox is control to display collection. Therefore now ListBox will display the Items of the MainViewModel.

但是,WPF 不知道如何显示 Items 的元素,因为 item 类型是用户定义的类型 (ResearchItem).因此,您必须定义如何显示它,如下所示.

But yet, WPF doesn't know how to display the element of the Items because item type is a user-defined type (ResearchItem). Therefore you have to define how to display it as below.

<ListBox Width="200" Height="100" ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

名称是研究项目.

现在我将数据填充到 Items 集合中,如下所示.

Now I will fill data into the Items collection as below.

public class MainViewModel : INotifyPropertyChanged
{
    public ObservableCollection<ResearchItem> Items { get; } = new ObservableCollection<ResearchItem>();

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    public MainViewModel()
    {
        this.Items.Add(new ResearchItem() { Name = "The first research" });
        this.Items.Add(new ResearchItem() { Name = "The second research" });
        this.Items.Add(new ResearchItem() { Name = "The third research" });
    }
}

执行此操作时,您将看到 ListBox 中填充的数据.

When you execute this, you would see what filled data in the ListBox.

现在一切准备就绪.我可以告诉你想要什么.

Now everything is ready. I can tell what you want.

为了获取ListBox的选中数据,我将添加一个属性如下.

To bring selected data of the ListBox, I will added one property as below.

public class MainViewModel : INotifyPropertyChanged
{
    public ObservableCollection<ResearchItem> Items { get; } = new ObservableCollection<ResearchItem>();

    private ResearchItem selectedItem;
    public ResearchItem SelectedItem
    {
        get => this.selectedItem;
        set
        {
            if (this.selectedItem == value) return;
            this.selectedItem = value;

            this.OnPropertyChanged("SelectedItem");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    public MainViewModel()
    {
        this.Items.Add(new ResearchItem() { Name = "The first research" });
        this.Items.Add(new ResearchItem() { Name = "The second research" });
        this.Items.Add(new ResearchItem() { Name = "The third research" });
    }
}

现在您必须将添加的 SelectedItem 属性绑定到 ListBox 的属性(SelectedItem).

Now you have to bind added SelectedItem property to the property(SelectedItem) of the ListBox.

代码如下所示.

<ListBox Width="200" Height="100" ItemsSource="{Binding Items}"
                SelectedItem="{Binding SelectedItem}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

一切都结束了.现在您可以将 ListBox 的选定元素带到 cs 文件中.

Everything is over. now you could bring the selected element of the ListBox to the cs file.

我们必须这样做的原因是将设计和逻辑分开.我认为你应该学习 MVVM 模式,因为它在 WPF 中是必不可少的.

The reason we have to do this is to separate design and logic. I think you should learn the MVVM pattern because it is essential in the WPF.

希望对你有帮助.

这篇关于将数据从 WPF 窗口发送到 C# 类文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆