Icet
Icet

Reputation: 688

XAML can't get text from label

I'm getting such error

The name 'ScoreBtn' does not exist in the current context

and

The name 'LvlBttn' does not exist in the current context

on c# side but I can get text of Label x:Name="Lines". Where is mistake and how can I fix it?

Thanks for any help,

 </Window.Resources>
<DockPanel LastChildFill="false">
    <Button DockPanel.Dock="Right" Visibility="Hidden" Width="300">Right</Button>
    <StackPanel DockPanel.Dock="Right" Width="311" >
        <Button x:Name="btnPlay" Content="Play" Click="btnPlay_Click" Width="50" Height="25" Margin="5"/>
        <Button x:Name="Score" HorizontalAlignment="Left" VerticalAlignment="Top" Height="90" Margin="0,20,0,0" Width="170" Click="buttonPlay_Click"  >
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <Grid>
                        <Image Name="img1" Source="Images/play.png" Stretch="Fill" />
------------------->>   <Label x:Name="ScoreBtn" FontFamily="Bradley Hand ITC" HorizontalAlignment="Center" FontSize="22" VerticalAlignment="Center" Opacity="0.8" Content="Score"/>
                    </Grid>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <Button x:Name="level" HorizontalAlignment="Left" VerticalAlignment="Top" Height="90" Margin="0,20,0,0" Width="170" Click="buttonPlay_Click"  >
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <Grid>
                        <Image Name="img1" Source="Images/play.png" Stretch="Fill" />
------------------->>   <Label Content="Level 1" x:Name="LvlBttn" FontFamily="Bradley Hand ITC" HorizontalAlignment="Center" FontSize="22" VerticalAlignment="Center" Opacity="0.8"/>
                    </Grid>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <Label Visibility="Hidden" Content="Lines " Height="56" x:Name="Lines" HorizontalAlignment="Center" FontSize="28" FontWeight="Bold" Margin="0,0,0,0"/>

Upvotes: 0

Views: 704

Answers (1)

This will get you the Label for the button named Score. "ScoreBtn"is the name of the label element. It's not as complicated as I thought it would be.

var label = (Label)Score.Template.FindName("ScoreBtn", Score);

You really ought to listen to Peter Duniho, write a viewmodel, and bind the label's Content property to a viewmodel property, but if you don't already have a viewmodel, you may not want to rewrite your entire project. Since you don't have a single Binding in your XAML, I imagine that might be the case.

Upvotes: 2

Related Questions