【问题标题】:silverLight: OpacityMask won't apply on custom controlsilverLight:OpacityMask 不适用于自定义控件
【发布时间】:2011-12-08 07:53:30
【问题描述】:

我通过在 Overlay 上应用 OpacityMask 使禁用的 ImageButton 自定义控件上的图像变灰。预期的效果是只有图像的主体变灰,因此图像上没有边框或框。

问题是:就图像 URI 是通过绑定的 getter(写在 {TemplateBinding XXX} 中的东西)访问的而言,掩码将不适用。但是,如果明确说明 URI,则掩码将起作用。那么问题来了,为什么在 TmplateBinding 的情况下会出现问题以及如何解决呢。

定义自定义图像按钮的 XAML 代码是:

            <my1:ImageButton Height="24" Width="24" x:Name="imageButton1" IsEnabled="False" ImageSource="/SilverlightApplication4;component/Undo_24x24.png" Margin="178,75,198,201">
            <Image Source="/SilverlightApplication4;component/Undo_24x24.png" Height="24" Width="24" />
        </my1:ImageButton>

自定义属性处理程序代码为:

    public class ImageButton: Button
{
    public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(null));
    public ImageSource ImageSource
    {
        get
        {
            return (ImageSource)this.GetValue(ImageSourceProperty);
        }
        set
        {
            this.SetValue(ImageSourceProperty, value);
        }
    }
}

自定义控件的样式代码(禁用状态):

                            <Rectangle x:Name="DisabledVisualElement" Fill="Red" Opacity="0" >
                            <Rectangle.OpacityMask>
                                <ImageBrush ImageSource="{TemplateBinding ImageSource}"/>                                   
                            </Rectangle.OpacityMask>
                        </Rectangle>

有趣的是,下面的代码sn-ps放在样式模板里面

<Image Source="{TemplateBinding ImageSource}" Height="24" Width="24" />

还有

                            <Rectangle x:Name="DisabledVisualElement" Fill="Red" Opacity="0" >
                            <Rectangle.OpacityMask>
                                <ImageBrush ImageSource="/SilverlightApplication4;component/Undo_24x24.png"/>                                   
                            </Rectangle.OpacityMask>
                        </Rectangle>

两者都能正常工作。所以问题似乎在于 ImageSource="{TemplateBinding ImageSource}" 以某种方式无法检索正确的 URI 或由于其他原因无法正常工作。那么,如何纠正呢?

【问题讨论】:

    标签: silverlight controls imagebutton opacitymask


    【解决方案1】:

    TemplateBinding 的功能不如常规绑定。 TemplateBinding 无法自动将字符串/uri 转换为实际的位图。

    解决方案(使用常规绑定):

    <Rectangle x:Name="DisabledVisualElement" Fill="Red" Opacity="0" >
        <Rectangle.OpacityMask>
            <ImageBrush ImageSource="{Binding Path=ImageSource, RelativeSource={RelativeSource TemplatedParent}}"/>                                   
        </Rectangle.OpacityMask>
    </Rectangle>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 2014-02-28
      • 2013-03-23
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多