我有一个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>