我有一个带有用户控件的页面,并且用户控件具有依赖项属性。设置属性值的逻辑稍微复杂一些,所以我想从页面的代码隐藏中完成。
预期的流程是:
主页: - 在加载事件中,设置控件的属性
儿童控制 - 在"已加载事件"中,将属性推送到 XAML
我已经在 WPF 和 WinRT 中尝试过此操作,并在调试器中使用断点。它在 WPF 中按预期工作,但在 WinRT 中,子控件的 Loaded 事件在主页的事件之前调用,因此序列失败。
ChildControl.xaml
<UserControl x:Class="UserControlFromWinRT.ChildControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Loaded="UserControl_Loaded">
<Grid>
<TextBlock x:Name="greetingTextBlock"/>
</Grid>
ChildControl.xaml.cs
public partial class ChildControl : UserControl
{
public ChildControl() {
InitializeComponent();
}
public string Greeting {
get { return (string)GetValue(GreetingProperty); }
set { SetValue(GreetingProperty, value); }
}
public static readonly DependencyProperty GreetingProperty =
DependencyProperty.Register("Greeting", typeof(string), typeof(ChildControl), new PropertyMetadata(""));
private void UserControl_Loaded(object sender, RoutedEventArgs e) {
greetingTextBlock.Text = Greeting;
}
}
MainPage.xaml
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<local:ChildControl x:Name="childControl" Margin="20,30,0,0" FontSize="30"/>
</Grid>
MainPage.xaml.cs
private void Page_Loaded(object sender, RoutedEventArgs e) {
childControl.Greeting = "Hello";
}
将 PropertyChangedCallback 添加到 PropertyMetadata 构造函数
喜欢:
public static readonly DependencyProperty GreetingProperty = DependencyProperty.Register("Greeting", typeof(string), typeof(ChildControl), new PropertyMetadata("", OnGreetingChanged));
private static void OnGreetingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// do something e.NewValue
}