我会创建两个DependencyProperties
,一个用于Text
,另一个用于Image
Source
。
Image
Source
DependencyProperty
在更新时会自动设置内部Image
控件的源。同样地,Text
DependencyProperty
也会设置内部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
控件只是绑定到父级(主UserControl
)的Text
DependencyProperty
。