RbmxXx's Tech Sky
唯有技术让我成长……

导航

 

在zhanbos的2005年Avalon有奖问答系列第一期的那道题目中,为了加深我们对Avalon中鼠标指针的样式的理解,题目中让我们用style对button的定义来实现数据绑定。对于初识avalon的我,对其结构并不是很了解,本以为xaml只是一种类似于xml的标记语言,其实并不是如此,它的每一个结构,每一个属性都是.NET类库相匹配的。只是用xml的结构形式来自定义应用程序的样式,可以说是给了我们程序员更广阔的空间,也省去了大部分程序为一个好的UI发愁的问题,同时也解决了一个程序的多种表现形式,WEB,WINDOWS……

Button是如此定义的:


<Button Grid.Row="0" Grid.Column="0" Name="None"/>
<Button Grid.Row="0" Grid.Column="1" Name="No"/>
<Button Grid.Row="0" Grid.Column="2" Name="Arrow"/>
<Button Grid.Row="0" Grid.Column="3" Name="AppStarting"/>

<Grid.Resources>

    <Style TargetType="{x:Type Button}">

    <Setter Property="Margin" Value="1"/>

    <Style.Triggers>

          <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Background" Value="LightGreen"/>

          </Trigger>

    </Style.Triggers>

            </Style>

</Grid.Resources>

查看了winfx的library,显然Button是一个类,那么它其中有两个属性Content、Cursor显然是指Button的文本和当鼠标移上去时的样式。
找到了需要的属性后,然后就是要对他们绑定数据了。
那我们要绑定的数据在哪儿呢?
就在Button的定义中的name属性。

在xaml中绑定使用如下标记以却别一般属性
{Binding}
当然Binding也必然是一个类在System.Windows.Data命名空间中
其有一个属性是RelativeSource

Description of the object to use as the source, relative to the target element.
Permissible values are
/Self - use the target element itself
/TemplatedParent- use the target element's templated parent
/ParentData - use the DataContext from the surrounding scope
/PreviousData - use the DataContext from the previous scope
The last three may be chained (but not intermixed).


它的三个使用方法msdn已经讲得很清楚了。它是用在Button的DataContext属性中的。

当要为Button绑定数据时必须为其指定数据源,也就是msdn说的:

Gets or sets the data context for an element when it participates in data binding.

然后再为Button的两个属性绑定数据。

更具msdn的avalon的绑定数据的例子可知:
{Binding Path=Name}

因此完整的绑定代码如下:

<Style TargetType="{x:Type Button}"> 

<Setter Property="Margin" Value="1"/> 

<Setter Property="DataContext" Value="{Binding RelativeSource=/Self}"/> 

<Setter Property="Content" Value="{Binding Path=Name}"/> 

<Style.Triggers> 

<Trigger Property="IsMouseOver" Value="True"> 

<Setter Property="Background" Value="LightGreen"/> 

<Setter Property="Cursor" Value="{Binding Path=Name}"/> 

</Trigger> 

</Style.Triggers> 

</Style> 
posted on 2005-06-20 01:04  RbmxXx  阅读(1703)  评论(0)    收藏  举报