windowsphone7数据绑定的一种用法

来源:互联网 发布:excel数据分析回归 编辑:程序博客网 时间:2024/04/30 09:44

假如我们自定义了一个UserControl,我们可能需要定义一些这个用户控件特有的依赖属性。

但有些时候,我们可能想直接复用父控件的依赖属性;比如有个控件叫MyControl, 里面的根容器为LayoutRoot。在xaml中我想这么定义它: <uc:MyControl Background="White"/>,然后LayoutRoot的背景也被赋值为White。

一种实现的方法是重新定义了Background这个依赖属性,以覆盖原有的Background属性,同时注册PropertyChanged事件,在触发该事件的时候将背景的值赋值给LayoutRoot。

另一种方法则更加简单,直接让LayoutRoot通过绑定ElementName来绑定MyControl的Background的值来实现背景的改变。

实现的代码如下:

<UserControl x:Class="TestProject.Controls.MyControl"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    mc:Ignorable="d"    Background="Black"    x:Name="ParentCTL">    <Grid x:Name="LayoutRoot" Background="{Binding Background,ElementName=ParentCTL}"/></UserControl>
我们可以这样来使用它:

<uc:MyControl x:Name="myControl" Background="White"/>

如果我们只是定义了MyControl,但是没有定义Background的值,那么它将使用默认值(这个例子的默认值为Black,如代码所示)。



原创粉丝点击