[英]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.