我将一个类传递给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
}
}
}
答案 0 :(得分:0)
最简单的方法是使用私有字段。您应该创建一个私有只读字段来设置值。
public TitleWindow(Product newproduct)
{
this.DataContext = newproduct;
_product = newproduct;
InitializeComponent();
}
private readonly Product _product;
然后您可以在RewriteTitle中找到_product
private void RewriteTitle(object sender, TextChangedEventArgs e)
{
// Here I want to access newproduct
// Use _product = xx Or _product.Foo = xx;
}