Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a variable with a textblock

I was wondering how I would be able to bind a text block to a variable within my C# class.

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!

like image 475
Aero Chocolate Avatar asked Dec 03 '10 10:12

Aero Chocolate


People also ask

Is TextBlock editable?

TextBlock is not editable.

What is TextBlock WPF?

The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.


1 Answers

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

}
like image 94
Michael Hilus Avatar answered Oct 04 '22 15:10

Michael Hilus