gpt4 book ai didi

wpf - 如何在 WPF 中将内部控件的属性公开给其父 UserControl

转载 作者:行者123 更新时间:2023-12-03 06:49:31 24 4
gpt4 key购买 nike

我有一个 DialogPrompt UserControl,它将有一个 Image 和一个 TextBlock。这是模板:

    <UserControl>   
<Button x:Name="_OkButton" Content="OK"/>
<DockPanel >
<Image/>
<TextBlock x:Name="_DialogTextBox" />
</DockPanel>
</UserControl>

如何在我的 UserControl 中公开 TextBlock 的 Image 和 Text 属性的 Source 属性?

最佳答案

我会创建两个 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);
}
}
}

每当 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控件只是绑定(bind)到 Text DependencyProperty父级(主要 UserControl )。

关于wpf - 如何在 WPF 中将内部控件的属性公开给其父 UserControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30240274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com