繁体   English   中英

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

[英]How to reference and use label in c# wpf

我目前是第一次与wpf玩,并且遇到了一些问题。 我无法弄清楚如何引用wpf标签元素。 我将标签名称更改为“ label1”,并尝试在我的C#代码中引用它,但可惜没有结果,例如错误。

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#

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 
{



}   

}

请轻描淡写,我曾经是C#的中级人员,但是几年没使用它了。

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

这段代码没有任何意义:

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

您不能像这样访问label1 您必须在属性getter / setter或方法中执行此操作:

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

另外,不要删除构造函数InitializeComponent()调用,否则您的窗口将不会初始化。 这很重要(除非您向项目添加新窗口时添加了为您创建的部分类,还添加了部分类):

public MainWindow()
{
    InitializeComponent();
}

暂无
暂无

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

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