WPF自定义控件绑定图像源

时间:2016-10-14 23:31:09

标签: c# wpf xaml

我有一个基于按钮的自定义控件,我在里面放了一个图像。我可以在xaml中设置图像的来源,但如果我尝试绑定它,它就不起作用。

Generic.xaml

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControl">

<Style TargetType="{x:Type local:MyCustomControl}" BasedOn = "{StaticResource {x:Type Button}}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
                <Grid x:Name="InnerGrid">
                    <Image Source="pathname"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

</Style>
</ResourceDictionary>

这很好用,但是如果我用<Image Source="pathname"/>替换<Image Source={Binding MyImage, RelativeSource={RelativeSource Self}}"/>并引用类中的Delegate属性,它就会中断。

MyCustomControl.cs

public class MyCustomControl : Button
{
    static DependencyProperty m_myimage = null;
    private DependencyProperty MyImageProperty
    {
        get
        {
            return m_myimage;
        }
    }
    public BitmapImage MyImage
    {
        get
        {
            return (BitmapImage)GetValue(MyImageProperty);
        }

        set
        {
            SetValue(MyImageProperty, value);
        }
    }

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);
        MyImage = new BitmapImage(new Uri(pathname));
    }

    private static void RegisterDependencyProperties()
    {
        if (m_myimage == null)
        {
            m_myimage = DependencyProperty.Register("MyImage",
                typeof(BitmapImage), typeof(MyCustomControl), null);
        }
    }

    static MyCustomControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), 
            new FrameworkPropertyMetadata(typeof(MyCustomControl)));
        RegisterDependencyProperties();
    }
}

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

大约2个小时后自己搞清楚了。 xaml绑定应该看起来像,

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
            <Grid x:Name="InnerGrid">
                <Image Source="{Binding MyImage, RelativeSource={RelativeSource TemplatedParent}}"/>
            </Grid>
        </ControlTemplate>
    </Setter.Value>
</Setter>

请注意,绑定相对资源从RelativeSource={RelativeSource Self}转到RelativeSource={RelativeSource TemplatedParent}