Problem calling labelname.Text in my source code

Viewed 44

I am very new to WPF in C# and I am stuck working on an application made to (among other things) calculate the total number of items on a list. I want to print a label with that number/the sum and in tutorials I have seen people call labelname.Text in their source code, but when I try to do the same I don't have that option.

My Windows application design

It is in Danish, but what I need is the sum of "Antal" from the table printed on a label next to "Samlet antal varer:" to the right of the table.

My DataGrid:

    <DataGrid ColumnWidth="*" CanUserAddRows="False" x:Name="StockList" Margin="57,23,453,261">
            <!--Column Header Text & Bindings -->
            <DataGrid.Columns>
                <DataGridTextColumn Header="Vare" Binding="{Binding vare}" Width="auto"/>
                <DataGridTextColumn Header="Pris" Binding="{Binding pris}" Width="50"/>
                <DataGridTextColumn Header="Antal" Binding="{Binding antal}" Width="50"/>
                <DataGridTextColumn Header="Samlet pris" Binding="{Binding samletPris}"  Width="*"/>
            </DataGrid.Columns>
        </DataGrid>

My Labels:

    <!-- labels -->
        <Label x:Name="lblSamletVarer" HorizontalAlignment="Left" Margin="637,142,0,0" VerticalAlignment="Top"/>
        <Label x:Name="lblSamletPrisEkskl"  HorizontalAlignment="Left" Margin="637,192,0,0" VerticalAlignment="Top"/>
        <Label x:Name="lblSamletPrisInkl"  HorizontalAlignment="Left" Margin="637,242,0,0" VerticalAlignment="Top"/>

I hope it all makes sense. Please reach out if you need more information in order to help.

1 Answers

Try

<TextBlock x:Name="Label1" Text="{Binding Path=Label1Value}"/>

in XAML to replace your label markup (a better option than a Label) then provide a value for it in your ViewModel or code-behind; you can provide a literal value as I've shown below or use whatever logic you like to compute a value at runtime and return that. A TextBlock uses a OneWay binding by default since it is read-only, so you don't need to provide a setter or PropertyChanged notification.

public string Label1Value
{
  get { return "This string in your TextBlock"; }
}

Obviously, use whatever more appropriate identifiers you like for "Label1Value" and "Label1"!

It isn't clear what you are trying to bind the DataGridTextColumn elements to in your code. You can bind directly from one control to another using the "ElementName" syntax within the binding expression, but since you need to compute something from your DataGridTextColumn, I assume you'll bind that to something in your ViewModel or code-behind and calculate the value there before passing it back.

Related