如何在WPF Xaml中访问控件引用?

Joa*_*nge 10 .net c# wpf xaml

我有一些控件,我将其Name属性设置为唯一的名称,但我无法在匹配的C#代码文件中访问它们.

我试过了:

this.ControlName
MainWindow.ControlName
ControlName
Run Code Online (Sandbox Code Playgroud)

但它确实"看到"了他们.

我该怎么做呢?

我还需要为包装面板,网格视图等中的嵌套控件做些特别的事情吗?

编辑:

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>
Run Code Online (Sandbox Code Playgroud)

Aks*_*y J 16

要访问后面代码中的任何元素,您需要设置x:Name指令.它告诉XAML解析器将表示指定元素的字段添加到Window类的自动生成部分,就像Winforms一样.

在WPF应用程序中,不需要为每个元素命名.您应该只列出要以编程方式与之交互的元素.

一个例子:

<TextBlock x:Name="tblText" Text="Stackoverflow rocks."></TextBlock>
Run Code Online (Sandbox Code Playgroud)

编辑:
我使用以下代码,我能够访问列表视图:

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>
Run Code Online (Sandbox Code Playgroud)

  • 不,它对我不起作用.我试过x:Name,但它不起作用. (2认同)
  • 值得注意的是,默认情况下,只需设置x:Name就不会使该控件在项目中随处可访问,只需在代码隐藏中专门针对定义x:Name的xml. (2认同)

Lav*_*Lav 5

你有没有x:Name="ControlName"在 xaml 中设置他们的属性?

以下是有关 x:Name 指令的更多信息。

例如:

<Button x:Name="Button1">Click Me</Button>
Run Code Online (Sandbox Code Playgroud)