我会创建两个DependencyProperties,一个用于Text,一个用于ImageSource。
Image Source DependencyProperty 将在更新时自动设置内部 Image 控件的源。同样,TextDependencyProperty 也将设置内部TextBlock 控件的Text。
设置如下:
public partial class MyUserControl : UserControl
{
#region ImageSource
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register
(
"ImageSource",
typeof(Uri),
typeof(MyUserControl),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnImageSourceChanged))
);
public Uri ImageSource
{
get { return (Uri)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
#endregion ImageSource
#region Text
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register
(
"Text",
typeof(string),
typeof(MyUserControl),
new FrameworkPropertyMetadata("")
);
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
#endregion Text
public MyUserControl()
{
InitializeComponent();
}
private static void OnImageSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var myUserControl = sender as MyUserControl;
if (myUserControl != null)
{
myUserControl.ImageSource.Source = new BitmapImage((Uri) e.NewValue);
}
}
}
每当Image Source 更改时,这将自动更新内部Image 控件的源。注意,由于Image 控件本身使用ImageSource 类型,因此我们需要在此处进行一些转换。
XAML 然后可以更新为:
<UserControl x:Name="ControlName">
<Button x:Name = "OkButton" Content="OK"/>
<DockPanel >
<Image x:Name = "MyImage" />
<TextBlock x:Name = "DialogTextBox" Text="{Binding ElementName=ControlName, Path=Text}"/>
</DockPanel>
</UserControl>
这里,内部TextBlock 控件只是绑定到父级的Text DependencyProperty(主UserControl)。