【问题标题】:WPF Custom control binding image sourceWPF自定义控件绑定图片源
【发布时间】:2016-10-15 08:28:30
【问题描述】:

我有一个基于按钮的自定义控件,我在里面放了一个图像。我可以在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>

这很好用,但是如果我用&lt;Image Source={Binding MyImage, RelativeSource={RelativeSource Self}}"/&gt; 替换&lt;Image Source="pathname"/&gt;,并在类中引用一个委托属性,它就会中断。

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();
    }
}

我怎样才能让它工作?

【问题讨论】:

  • 为什么我突然被否决了?

标签: c# wpf xaml


【解决方案1】:

大约 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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-03
    • 2012-01-22
    • 2013-01-11
    • 2013-03-15
    • 2010-12-28
    • 2011-08-06
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多