c# - 如何访问 WPF Xaml 中的控件引用?

标签 c# .net wpf xaml

我有一些控件,我将它们的 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/

相关文章:

c# - 在 WPF 中,如何获取当前主题的按钮背景?

c# - 如何在超时时根据用户类型将用户重定向到 ASP.net MVC 应用程序中的不同 url

c# - 使用属性读取 XML 的最简单方法

c# - 如何知道何时调用可观察集合中的基本方法或重写方法

c# - 关于 .NET 框架中继承的一般问题

.net - 从网络流中读取 : packet fragmentation

c# - WPF 数据网格 : Clear column sorting

c# - NUnit - 在 Visual Studio 中使用测试适配器运行测试时获取 results.xml

c# - 通过migradoc为pdf添加上标和下标

c# - 后台工作人员仍然忙碌