刘荣逵技术博客

Work for a better day

WPF中如何在后台取得前台控件实例(一)

一、概述

     相信很多用过WPF的人都知道在后台中要取得前台显示.XAML中的一些控件不是很容易的,他并不像我们在Winform中那样可以直接调用前台Form中的控件。这两天研究了一些这方面的东西在此与大家分享。很可能您的方法比我的更加简单易懂,如果这样的话不妨交流一下。

二、用VisualTreeHelper

    VisualTreeHelper提供一些实用工具方法,用于执行涉及可视化树中的节点的常规任务。

   

MSDN上这样说:
可视化树中的节点可以是 Visual 或 Visual3D 对象。特定于可视对象的类型的方法类型化为 Visual 或 Visual3D。
但是,VisualTreeHelper 类中的一些方法可以接受表示任意一种可视对象类型的 DependencyObject 值。 

WPF 支持对对象的几种不同树结构进行编程访问。这主要作为可视化树和逻辑树公开。在某些情况下,逻辑树在 WPF 应用程序中是一种更有用的元素表示形式,
但在概念上逻辑树在 Visual 类之上的某一级别上实现。与可视化树不同,逻辑树可以表示非可视化数据对象,如 ListItem。有关逻辑树的更多信息,
请参见 WPF 中的树。一个类似的实用工具方法类 LogicalTreeHelper 也支持逻辑树。 

 例如在我的前台中有一个ToolTip控件,我想要在后台更改他的<TextBox>中的TEXT属性
       <ToolTip x:Key="InforTip" x:Name="TestTip" Loaded="TestTip_Loaded">
<StackPanel Orientation="Horizontal">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Name="tbSoftName" Grid.Column="0" Grid.Row="0" />
<TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding Path=Name}"/>
<TextBlock Name="tbSoftVersion" Grid.Column="0" Grid.Row="1"/>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Path=CurrFileName}"/>
<TextBlock Name="tbSoftwareNote" Grid.Column="0" Grid.Row="2"/>
<TextBlock Grid.Column="1" Grid.Row="2" Text="{Binding Path=Mo}"/>
</Grid>
</StackPanel>
</ToolTip>

那么在后台

        private void TestTip_Loaded(object sender, RoutedEventArgs e)
{
DependencyObject obj
= e.OriginalSource as DependencyObject;
object temp = null;
while (!((VisualTreeHelper.GetChild(obj, 0)) is TextBlock))
{
obj
= VisualTreeHelper.GetChild(obj, 0);
}

//get and set TextBlock Control--tbSoftwareName
temp = VisualTreeHelper.GetChild(obj, 0);
TextBlock tbSoftName
= temp as TextBlock;
tbSoftName.Text
= AppRes::Resources.tbSoftName;
//end get and set TextBlock Control--tbSoftwareName

//get and set TextBlock Control--tbSoftwareVersion
temp = VisualTreeHelper.GetChild(obj, 2);
TextBlock tbSoftVersion
= temp as TextBlock;
tbSoftVersion.Text
= AppRes::Resources.tbSoftVersion;
//end get and set TextBlock Control--tbSoftwareVersion

//get and set TextBlock Control--tbSoftwareNote
temp = VisualTreeHelper.GetChild(obj, 4);
TextBlock tbSoftwareNote
= temp as TextBlock;
tbSoftwareNote.Text
= AppRes::Resources.tbSoftNote;
//end get and set TextBlock Control--tbSoftwareNote



}

三、小结

    由于时间关系今天暂且说这一种方法,如果您有更好的方法请联系我哦~ 我们共同交流!

posted on 2008-10-22 08:49  Rock.Liu  阅读(4944)  评论(4编辑  收藏  举报

导航