1

我通过在 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>

有趣的是,以下代码片段都放在样式模板中

<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 或由于其他原因无法正常工作。那么,如何纠正这种情况呢?

4

1 回答 1

0

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

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

<Rectangle x:Name="DisabledVisualElement" Fill="Red" Opacity="0" >
    <Rectangle.OpacityMask>
        <ImageBrush ImageSource="{Binding Path=ImageSource, RelativeSource={RelativeSource TemplatedParent}}"/>                                   
    </Rectangle.OpacityMask>
</Rectangle>
于 2012-01-13T11:15:58.913 回答