简体   繁体   中英

How to reference and use label in c# wpf

I'm currently playing with wpf for the first time and I'm coming into some issues. I cannot figure out how to reference the wpf label element. I changed my label name to "label1" and try referencing it in my c# code, but alas no result just errors such as.

xaml

<Controls:MetroWindow x:Class="Rustomatic.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Rustomatic" 
    Height="350" 
    Width="525" >
<Grid>
    <Label x:Name="label1" Content="Label" HorizontalAlignment="Left" Margin="229,128,0,0" VerticalAlignment="Top"/>

</Grid>
<Window.InputBindings>
    <KeyBinding Gesture="F5" Command="{Binding Hit}" />
</Window.InputBindings>

c#

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;


namespace Rustomatic
{

public partial class MainWindow : MetroWindow
{
    label1.content = "hi";

}

public class Hit 
{



}   

}

Please take it lightly I was an intermediate at C# once but I haven't used it in a couple of years.

You give names to elements in xaml by using x:Name , this will cause them to be publicly named in designer generated cs-file (it is made out of xaml) and you can access them as you did it in past in winforms.

This code doesn't makes any sense:

public partial class MainWindow : MetroWindow
{
    label1.content = "hi";
}

You can't access label1 like this. You have to do it in the property getter/setter or method:

public partial class MainWindow : MetroWindow
{
    public void SomeMethod()
    {
        label1.Content = "hi";
    }
}

Also, don't remove constructor InitializeComponent() call, otherwise your window will not get initialized. This is important (unless you add partial class in addition to partial class made for you when you add new window to project):

public MainWindow()
{
    InitializeComponent();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM