WPF - Controltemplate child访问用户控件的自定义依赖项属性

时间:2014-08-20 17:06:22

标签: c# wpf xaml

我有一个WPF UserControl,我添加了一个新的string依赖项属性。我想从在其自己的XAML页面上为UserControl定义的ControlTemplate中的另一个控件(Image)访问该属性。将在ControlTemplate中的Image的Source属性上设置string。设置属性有效,但ControlTemplate中的控件未接收该值。为什么会这样?

这是我的代码:

public static readonly DependencyProperty ButtonImageSourceProperty = DependencyProperty.Register("ButtonImageSource", typeof(string), typeof(MyControl));

public string ButtonImageSource
        {
            get { return (string)GetValue(ButtonImageSourceProperty); }
            set { SetValue(ButtonImageSourceProperty, value); }
        }

这是XAML:

<UserControl.Resources>
        <Style TargetType="custom:MyControl">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="custom:MyControl">
                        <Grid>
                        <ContentPresenter></ContentPresenter>
                            <Image Source="{TemplateBinding ButtonImageSource}" Width="30" Height="30"></Image> <!--Image's source to be set by dependency property-->
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>

1 个答案:

答案 0 :(得分:0)

使用 RelativeSource模式TemplatedParent而不是TemplateBinding ,如下所示:

Source="{Binding ButtonImageSource,
                 RelativeSource={RelativeSource Mode=TemplatedParent}}"

对于两者之间的差异,您可以阅读herehere