我现在第一次玩wpf而且我遇到了一些问题.我无法弄清楚如何引用wpf标签元素.我将我的标签名称更改为"label1",并尝试在我的c#代码中引用它,但是没有结果只是错误,例如.
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>
Run Code Online (Sandbox Code Playgroud)
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
{
}
}
Run Code Online (Sandbox Code Playgroud)
请小心点我曾经是C#的中间人,但是我在几年内没有使用它.
你通过使用给xaml中的元素x:Name命名,这将使它们在设计器生成的cs文件中公开命名(它由xaml构成),你可以像以前在winforms中那样访问它们.
这段代码没有任何意义:
public partial class MainWindow : MetroWindow
{
label1.content = "hi";
}
Run Code Online (Sandbox Code Playgroud)
你不能这样访问label1.您必须在属性getter/setter或方法中执行此操作:
public partial class MainWindow : MetroWindow
{
public void SomeMethod()
{
label1.Content = "hi";
}
}
Run Code Online (Sandbox Code Playgroud)
另外,不要删除构造函数InitializeComponent()调用,否则您的窗口将不会被初始化.这很重要(除非您在向项目添加新窗口时为部分类添加部分类):
public MainWindow()
{
InitializeComponent();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1881 次 |
| 最近记录: |