Источник изображения привязки пользовательского элемента управления WPF

#c# #wpf #xaml

#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}}"/> и ссылаюсь на свойство делегата в классе, оно прерывается.

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. Почему я вдруг получил отрицательный голос?

Ответ №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}