你应该使用依赖属性。以下是一个详细说明的示例解决方案:
用户控制
<UserControl
x:Class="TestApps.ImageButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestApps"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400" x:Name="MyControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Source="{Binding ElementName=MyControl, Path=Source, Mode=OneWay}"/>
<Button Content="{Binding ElementName=MyControl, Path=ButtonContent, Mode=OneWay}"
Grid.Row="1" Height="50" HorizontalAlignment="Center"/>
</Grid>
</UserControl>
后面的用户控制代码
public sealed partial class ImageButton : UserControl
{
public ImageButton()
{
this.InitializeComponent();
}
public string Source
{
get { return (string)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
// Using a DependencyProperty as the backing store for Source. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register("Source", typeof(string), typeof(ImageButton), new PropertyMetadata(default(string)));
public string ButtonContent
{
get { return (string)GetValue(ButtonContentProperty); }
set { SetValue(ButtonContentProperty, value); }
}
// Using a DependencyProperty as the backing store for Source. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ButtonContentProperty =
DependencyProperty.Register("ButtonContent", typeof(string), typeof(ImageButton), new PropertyMetadata(default(string)));
}
父 XAML
<StackPanel Margin="100,10,10,10">
<local:ImageButton Source="../Assets/SplashScreen.scale-200.png" ButtonContent="Test Button!"/>
</StackPanel>
输出