c# - 如何访问传递给 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
}
}
}
解决方案
最简单的方法是使用私有字段。您应该创建一个私有只读字段来设置值。
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;
}
推荐阅读
- c - C中的解码声明(数组和函数指针的组合)
- typescript - 使用量角器打字稿框架中的打字稿遍历 HTML 表格以获取单元格
- javascript - $request->ajax() 在 ajax 调用时返回 false
- android - 无法通过 Android Oreo 中的 JobScheduler 启动服务
- python - 在 Python (Pandas) 中创建循环,遍历行名并创建分组多索引
- firebase - Firebase 函数从不同路径接收数据和求和
- sockets - Cloud SQL 套接字如何知道要连接到哪个域?
- javascript - 克隆所选元素
- javascript - 使用 JavaScript 交替向列表项添加类
- arrays - 快速复制具有相同地址的对象