首页 > 解决方案 > 如何访问传递给 WPF 窗口的类?

问题描述

我将一个类传递给 WPF 窗口,并将类的属性绑定到 WPF 窗口中的字段。我的工作正常,但我想编辑类的属性,显示 WPF 窗口中的更改,然后将类返回到调用 WPF 窗口的应用程序。

这是显示 WPF 窗口的代码。当我尝试从 RewriteTitle 方法访问 newproduct 时,我不能。

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.Shapes;

namespace Inventory_Controller
{
    /// <summary>
    /// Interaction logic for TitleWindow.xaml
    /// </summary>
    public partial class TitleWindow : Window
    {
        public TitleWindow(Product newproduct)
        {
            this.DataContext = newproduct;  //This didn't help

            InitializeComponent();

        }

        private void RewriteTitle(object sender, TextChangedEventArgs e)
        {

            // Here I want to access newproduct 


        }
    }
}

标签: c#wpfclass

解决方案


最简单的方法是使用私有字段。您应该创建一个私有只读字段来设置值。

    public TitleWindow(Product newproduct)
    {
        this.DataContext = newproduct; 

        _product = newproduct;

        InitializeComponent();
    }

    private readonly Product _product;

然后你可以_product在 RewriteTitle中找到

    private void RewriteTitle(object sender, TextChangedEventArgs e)
    {

        // Here I want to access newproduct 
        // Use _product = xx Or _product.Foo = xx;

    }

推荐阅读