如何将变量与文本块绑定

Aer*_*ate 8 data-binding wpf textblock

我想知道如何将文本块绑定到我的C#类中的变量.

基本上我的.cs文件中有一个"cart"变量.在那个Cart类中,我可以访问不同的总数.

以下是我对绑定的看法,但它似乎没有绑定到变量......

<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>
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?再次感谢您的帮助!

Mic*_*lus 11

如果您希望TextBox在购物车类更改时自动更新,则您的类必须实现 INotifyPropertyChanged接口:

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");
        }
    }

}
Run Code Online (Sandbox Code Playgroud)


dec*_*one 7

ElementNamein binding用于引用其他控件,而不是后面代码中的变量.要在代码后面引用变量,需要将该变量赋值给Control的DataContext属性.

替换以下每行代码:

<TextBlock Name="Subtotal" FontFamily="Resources/#Charlemagne Std" FontSize="20" Text="{Binding ElementName=cart, Path=SubTotal}"></TextBlock>
Run Code Online (Sandbox Code Playgroud)

用:

<TextBlock Name="Subtotal" FontFamily="Resources/#Charlemagne Std" FontSize="20" Text="{Binding Path=SubTotal}"></TextBlock>
Run Code Online (Sandbox Code Playgroud)

在Window的构造函数或Load事件中,编写以下代码:

this.DataContext = cart;
Run Code Online (Sandbox Code Playgroud)