如何从usercontrol中引用命名对象? [英] how to reference a named object from within a usercontrol?

查看:65
本文介绍了如何从usercontrol中引用命名对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。想象一下:


  • 我有一个MainWindow,它包含一个面板(名为"myCanvas")和一个usercontrol(名为"myUC")。
  • myUC是myCanvas的
  • 目标是点击myUC来设置myCanvas的属性。

不幸的是,我无法弄清楚如何从myUC中引用myCanvas。在Flash / ActionScript中,我只想使用类似"parent.myCanvas"的东西。 (或其他),但我在C#/ WPF中找不到任何等效符号。

Unfortunately, I cannot figure out how to reference myCanvas from within myUC. In Flash/ActionScript, I would just use something like "parent.myCanvas" (or whatever), but I can't find any equivalent notation in C#/WPF.

帮助?在此先感谢。

推荐答案

您是否正在谈论myUC的代码隐藏文件? (例如,myUC.xaml.cs) 

Are you talking about from the codebehind file for myUC? (myUC.xaml.cs for example) 

如果是这样,那很难,因为UserControls和类通常在xaml中工作。它们旨在封装功能,因此它们没有简单的方法来了解自己的类/文件之外的东西。

If so, that is difficult, because of the way UserControls and classes in general work in xaml. They are meant to encapsulate functionality, and as such they don't have an easy way to know about things outside of their own class/file.

也就是说,你可以从视觉树的名称,所以你可以做这样的事情:

That said, you can find things from the visual tree by name, so you could do something like this:

using System;
using System.Collections.Generic;
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;

namespace WpfApplication3
{
	/// <summary>
	/// Interaction logic for myUC.xaml
	/// </summary>
	public partial class myUC : UserControl
	{
		public myUC()
		{
			this.InitializeComponent();
		}

		private void Click(object sender, System.Windows.RoutedEventArgs e)
		{
			// TODO: Add event handler implementation here.
			var parent = VisualTreeHelper.GetParent(this) as FrameworkElement;

			Canvas target = null;
			while (parent != null)
			{
				var possibleCanvas = parent.FindName("myCanvas") as Canvas;
				if (possibleCanvas != null)
				{
					target = possibleCanvas;
					break;
				}

				parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
			}

			if (target != null)
			{
				target.Background = new SolidColorBrush(Colors.Green);
			}
		}
	}
}





<Window
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:local="clr-namespace:WpfApplication3"
	x:Class="WpfApplication3.MainWindow"
	x:Name="Window"
	Title="MainWindow"
	Width="640" Height="480">

	<Grid x:Name="LayoutRoot">
		<Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="86" Margin="90,86,0,0" VerticalAlignment="Top" Width="139" Background="Red"/>
		<local:myUC x:Name="myUC" Margin="258,219,266,122"/>
	</Grid>
</Window>


这篇关于如何从usercontrol中引用命名对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆