eYe*_*eYe 7 wpf xaml user-controls properties
我有一个DialogPrompt UserControl,它将具有一个Image和一个TextBlock.这是模板:
<UserControl>
<Button x:Name="_OkButton" Content="OK"/>
<DockPanel >
<Image/>
<TextBlock x:Name="_DialogTextBox" />
</DockPanel>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
如何在UserControl中公开TextBlock的Image和Text属性的Source属性?
d.m*_*ada 10
我会创建两个DependencyProperties
,一个用于Text
,一个用于Image
Source
.
该Image
Source
DependencyProperty
会自动设置内Image
时,它被更新控制的来源.同样,Text
DependencyProperty
也将设置Text
内部TextBlock
控件.
这是设置:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
每当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>
Run Code Online (Sandbox Code Playgroud)
这里,内部TextBlock
控件简单地绑定到Text
DependencyProperty
父控件(主控件UserControl
).
在后面的代码中,添加2个DependencyProperties并将它们绑定到图像源和TextBlock文本。
这是有关如何使用和创建依赖项属性的教程: http //www.wpftutorial.net/dependencyproperties.html
为了在xaml中进行绑定,下面是一个示例:
<Image Source="{Binding YourProperty, RelativeSource={RelativeSource FindAncestor, AncestorType=YourUserControl}}/>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4031 次 |
最近记录: |