简体   繁体   English

如何在C#WPF中引用和使用标签

[英]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. 我目前是第一次与wpf玩,并且遇到了一些问题。 I cannot figure out how to reference the wpf label element. 我无法弄清楚如何引用wpf标签元素。 I changed my label name to "label1" and try referencing it in my c# code, but alas no result just errors such as. 我将标签名称更改为“ label1”,并尝试在我的C#代码中引用它,但可惜没有结果,例如错误。

xaml a

<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# 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. 请轻描淡写,我曾经是C#的中级人员,但是几年没使用它了。

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. 通过使用x:Name为xaml中的元素x:Name ,这将使它们在设计器生成的cs文件(由xaml制成)中公开命名,并且您可以像以前一样在winforms中对其进行访问。

This code doesn't makes any sense: 这段代码没有任何意义:

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

You can't access label1 like this. 您不能像这样访问label1 You have to do it in the property getter/setter or method: 您必须在属性getter / setter或方法中执行此操作:

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. 另外,不要删除构造函数InitializeComponent()调用,否则您的窗口将不会初始化。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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