gpt4 book ai didi

wpf - 如何从我的代码隐藏构造函数访问DependencyProperty值?

转载 作者:行者123 更新时间:2023-12-04 18:54:42 25 4
gpt4 key购买 nike

我有一个名为 SmartForm 的UserControl,它具有一个名为 Status 的DependencyProperty。

在我的Window1.xaml中,我具有元素<local:SmartForm Status="Ready"/>

我想然后在SmartForm对象的构造函数中,状态将等于“Ready”,但它等于null。

为什么在SmartForm的构造函数中Status属性的值为NULL

如果不在UserControl构造函数中,何时可以访问值呢?

Window1.xaml:

<Window x:Class="TestPropertyDefine23282.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestPropertyDefine23282"
Title="Window1" Height="300" Width="300">
<Grid>
<local:SmartForm Status="Ready"/>
</Grid>
</Window>

SmartForm.xaml:
<UserControl x:Class="TestPropertyDefine23282.SmartForm"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid>
<TextBlock x:Name="TestingMessage"/>
</Grid>
</UserControl>

SmartForm.xaml.cs:
using System.Windows;
using System.Windows.Controls;

namespace TestPropertyDefine23282
{
public partial class SmartForm : UserControl
{
public SmartForm()
{
InitializeComponent();

TestingMessage.Text = Status; //WHY IS STATUS NOT YET SET HERE?

}

#region DependencyProperty: Status
public string Status
{
get
{
return (string)GetValue(StatusProperty);
}
set
{
SetValue(StatusProperty, value);
}
}

public static readonly DependencyProperty StatusProperty =
DependencyProperty.Register("Status", typeof(string), typeof(SmartForm),
new FrameworkPropertyMetadata());
#endregion

}
}

最佳答案

您可以将该测试消息设置为:

...
public static readonly DependencyProperty StatusProperty =
DependencyProperty.Register("Status", typeof(string), typeof(SmartForm),
new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(OnStatusChanged)));

public static void OnStatusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
((SmartForm)d).TestingMessage.Text = e.NewValue.ToString();
}
...

或作为:
<UserControl 
x:Class="TestPropertyDefine23282.SmartForm"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestPropertyDefine23282"
Height="300" Width="300"
>
<Grid>
<TextBlock
x:Name="TestingMessage"
Text="{Binding Path=Status, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:SmartForm}}}"
/>
</Grid>
</UserControl>

关于wpf - 如何从我的代码隐藏构造函数访问DependencyProperty值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/906745/

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