我有一个带有用户控件的页面,并且用户控件具有依赖项属性。设置属性值的逻辑有点复杂,所以我想从页面的代码隐藏中做。
预期的流程是:
的MainPage: - 在Loaded事件中,在控件上设置属性
ChildControl - 在Loaded事件中,将属性推送到XAML
我已经在WPF和WinRT中尝试了这个,并在调试器中使用了断点。它在WPF中按预期工作,但在WinRT中,子控件的Loaded事件在MainPage事件之前被调用,因此序列失败。
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";
}
答案 0 :(得分:1)
您需要将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
}