在Silverlight中绑定样式5

时间:2014-05-14 06:57:24

标签: c# silverlight

我知道Silverlight 5引入了样式中的数据绑定。我想以按钮的样式绑定内容模板中存在的图像源。 我正在使用下面的代码,我试图在样式中设置图像源属性。

//风格

<UserControl x:Class="MGPIControls_Simple.ButtonControl"
    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"
    xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
    Height="40" Width="40"
    mc:Ignorable="d" x:Name="ButtonControlSample">

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.Resources>

        <Style x:Key="ImageButtonStyle" TargetType="Button">
            <Setter Property="BorderBrush" Value="Transparent"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>

                        <!-- binding in style -->
                        <Image Source="{Binding ImageSource}"
                               VerticalAlignment="Stretch"
                               HorizontalAlignment="Stretch"
                               Stretch="Fill"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>

        </Style>
    </Grid.Resources>
    <Button x:Name="ButtonBase" Style="{StaticResource ImageButtonStyle}"
            HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Grid>

ImageSource是我创建的依赖属性。如果我不绑定图像源属性并将其保持静态到一些图像URL,事情工作正常但绑定不起作用。请告诉我上述方法的错误。

2 个答案:

答案 0 :(得分:0)

您必须使用像

这样的绑定
<TextBlock Text="{Binding Path=DataContext.BusyText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"

答案 1 :(得分:0)

那么,如何设置这个...你尝试做的是新的Silverlight 5功能样式中的绑定。即使使用较旧的Silverlight版本,也始终可以使用这种绑定。 您有DataTemplate,这意味着在从模板实例化实际UI元素时,将评估您声明的任何绑定。您的绑定Source="{Binding ImageSource}"将根据您的Button DataContext进行评估。 如果没有公共属性 ImageSource ,那么您的Button将不会显示任何图像。