我有一些控件,我将它们的 Name
属性设置为唯一的名称,但我无法在匹配的 C# 代码文件中访问它们。
我试过:
this.ControlName
MainWindow.ControlName
ControlName
但它确实“看到”了它们。
我该怎么做?
另外,我是否必须为环绕面板、 GridView 等内的嵌套控件做一些特殊的事情?
编辑:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 System.Reflection;
namespace EditorWindow
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow ( )
{
}
}
}
<Window x:Class="EditorWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Effects Editor">
<DockPanel>
<ListView x:Name="EffectsListView">
</ListView>
</DockPanel>
</Window>
最佳答案
要访问后面代码中的任何元素,您需要设置 x:Name 指令。 它告诉 XAML 解析器将表示命名元素的字段添加到 Window 类的自动生成部分,就像 Winforms 一样。
在 WPF 应用程序中,不需要为每个元素命名。你应该只命名那些你想以编程方式与之交互的元素。
一个例子:
<TextBlock x:Name="tblText" Text="Stackoverflow rocks."></TextBlock>
编辑:
我使用了以下代码并且能够访问 ListView :
namespace WpfApplicationUnleashed
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
EffectsListView.Width = 10;
}
}
}
<Window x:Class="WpfApplicationUnleashed.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApplicationUnleashed"
Title="Window1" >
<DockPanel>
<ListView x:Name="EffectsListView"></ListView>
</DockPanel>
</Window>
关于c# - 如何访问 WPF Xaml 中的控件引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5316062/