如何将变量绑定到文本块 [英] How to bind a variable with a textblock
本文介绍了如何将变量绑定到文本块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何将一个文本块绑定到我的C#类中的一个变量。
I was wondering how I would be able to bind a text block to a variable within my C# class.
我的基本上是一个cart变量。 cs文件。在该购物车类中,我可以访问不同的总计。
Basically I have a "cart" variable in my .cs file. Within that Cart class I have access to the different totals.
以下是我用于绑定的,但它似乎并不绑定到变量...
The following is what I have for binding, but it does not seem to bind to the variable...
<StackPanel
Width="Auto"
Height="Auto"
Grid.ColumnSpan="2"
Grid.Row="5"
HorizontalAlignment="Right">
<TextBlock
Name="Subtotal"
FontFamily="Resources/#Charlemagne Std"
FontSize="20"
Text="{Binding ElementName=cart, Path=SubTotal}">
</TextBlock>
<TextBlock
Name="Tax"
FontFamily="Resources/#Charlemagne Std"
FontSize="20"
Text="{Binding ElementName=cart, Path=Tax}">
</TextBlock>
<TextBlock
Name="Total"
FontFamily="Resources/#Charlemagne Std"
FontSize="20"
Text="{Binding ElementName=cart, Path=Total}">
</TextBlock>
</StackPanel>
正确的方法是什么?再次感谢您的帮助!
What is the correct way of doing it? Thanks again for the help!
推荐答案
如果您进一步希望文本框在您的购物车类更改时自动更新,您的课程必须实现 INotifyPropertyChanged
界面:
If you further want the TextBoxes to update automatically when your cart class changes, your class must implement the INotifyPropertyChanged
interface:
class Cart : INotifyPropertyChanged
{
// property changed event
public event PropertyChangedEventHandler PropertyChanged;
private int _subTotal;
private int _total;
private int _tax;
private void OnPropertyChanged(String property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public int SubTotal
{
get
{
return _subTotal;
}
set
{
_subTotal = value;
OnPropertyChanged("SubTotal");
}
}
public int Total
{
get
{
return _total;
}
set
{
_total = value;
OnPropertyChanged("Total");
}
}
public int Tax
{
get
{
return _tax;
}
set
{
_tax = value;
OnPropertyChanged("Tax");
}
}
}
这篇关于如何将变量绑定到文本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文