WPF 的初学者,请多多包涵。
在继续之前,我构建了一个概念验证应用程序。我决定先尝试使用 WPF 构建它。
这是场景:
我有:
鉴于我有一系列产品,并且对于我购买的每个产品,我需要将文本附加到 userControl 中的 txtBox 打印所有发生的操作,文本框应该看起来像
Start buying ..... Product 1 Sold Product 2 Sold Fineshed....
我的问题是,尽管我在每件商品售出后成功通知,但我似乎看不到如何绑定(bind)或使“产品 1 已售出,产品 2 出现在文本框中。
在 Windows 窗体中,我将拥有一个带有名为 ProductStatus 的属性的 userControl,并且每当收到通知时,我都会将文本附加到文本框。
当来自服务时,“我在进行 threadCross 操作时放置了 beginInvoke”。这是我必须调查的另一个问题
private ProductStatus _productStatus;
public ProductStatus Status
{
get { return _productStatus; }
set
{
_printStatus = value;
BeginInvoke((MethodInvoker)(() => txtProductResult.AppendText(string.Format("Product Sold {0}", Environment.NewLine))));
}
}
如何为我出售的每件商品将文本附加到 myTextBox?=================添加当前代码============================== =
void LogChanged(object sender, NotifyCollectionChangedEventArgs e)
{
foreach(object item in e.NewItems)
{
txtProduct.AppendText(item.ToString());
}
}
<TextBox Margin="12,41,12,59" Name="txtPrintResult" />
<TextBox Text="{Binding TicketPrintLog, Mode=OneWay}" Margin="12,41,12,12" />
ProductModel
=============
public string ProductLog{ get; set; }
ProductViewModel
==================
public string ProductLog
{
get { return _ProductModel.ProductLog; }
}
internal void AppendToProductLogText(string text)
{
_ProductModel.ProductLog += text + Environment.NewLine;
OnPropertyChanged("ProductLog");
}
void ProductSoldNotificationReceived(object sender, notificationEventArgs e)
{
//THIS FIRES WHENEVER I PRODUCT IS SOLD.
AppendToProductLogText(e.Message);
}
ProductView (userControl) XAML
================================
<TextBox Margin="12,41,12,59" Name="txtResult" Text="{Binding ProductLog, Mode=OneWay}" />
IN CODE BEHIND I DO
public void Action1()
{
txtResult.AppendText(_productViewModel.ProductLog);
}
public void SellProductAction()
{
txtResult.AppendText(_productViewModel.ProductLog);
}
我的问题是我仍然必须这样做 txtResult.AppendText(_productViewModel.ProductLog);
在执行 SellproductAction 时,这也破坏了数据绑定(bind)的要点我只收到有关最后一项的通知,它不会附加 Product1 已售出、Product 2 已售等……有任何想法吗?
最佳答案
首先,您仍然可以通过将新文本附加到现有文本来以 Windows 窗体的方式执行此操作:
txtProductResult = txtProductResult + Environment.NewLine + "Product sold";
(如果您从后台线程执行此操作,则需要使用 txtProductResult.Dispatcher.BeginInvoke 而不是 txtProductResult.BeginInvoke。)
但是,在 WPF 中执行此操作的惯用方法是使用数据绑定(bind)。因此,您将在 View 模型上创建 ProductSalesLog 属性,并将 TextBox 绑定(bind)到该属性。然后,每当您更新 View 模型中的 ProductSalesLog 属性时,TextBox 都会自动更新。请注意,您的 View 模型必须实现 INotifyPropertyChanged 并且必须引发 ProductSalesLog 属性的 PropertyChanged 事件。因此:
public class CustomerViewModel : INotifyPropertyChanged
{
private string _productSalesLog = String.Empty;
public string ProductSalesLog
{
get { return _productSalesLog; }
}
internal void AppendSalesLogText(string text)
{
_productSalesLog += text + Environment.NewLine;
OnPropertyChanged("ProductSalesLog");
}
}
在您看来:
<TextBox Text="{Binding ProductSalesLog, Mode=OneWay}" />
关于wpf - 绑定(bind)和 appendText 结果到 TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2260558/