我有一个非常简单的用户控件,该控件显示一个等待的动画,上面带有文本:
<UserControl x:Class="VNegoceNET.Controls.PleaseWait"
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"
xmlns:local="clr-namespace:VNegoceNET.Controls"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="RootElement" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.RowSpan="3" Background="White" Content="" Opacity="0.8"/>
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"
Grid.Row="0" FontSize="18" Foreground="Black"
Margin="8" x:Name="Caption" Text="Loading..."/>
<local:SpinningWait Grid.Row="1"/>
</Grid>
</UserControl>
我想这样使用它:
<controls:PleaseWait Text="Jegg Robot"/>
我的问题是,尽管我有Dependency属性,它仍然显示“ Loading ...”而不是“ Jegg Robot”:
public partial class PleaseWait : UserControl
{
public PleaseWait()
{
InitializeComponent();
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text", typeof(String), typeof(PleaseWait), new PropertyMetadata("Loading in progress..."));
public string Text
{
get => (string)this.GetValue(TextProperty);
set
{
Caption.Text = value;
this.SetValue(TextProperty, value);
}
}
}
我错过了什么?
答案 0 :(得分:1)
当从xaml(<controls:PleaseWait Text="Jegg Robot"/>
)中设置属性时,WPF不对DP(公共字符串Text)使用公共属性包装器,而是直接使用SetValue()。因此不会调用setter中的代码。
需要的是propertyChangedCallback:
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(String), typeof(PleaseWait),
new PropertyMetadata("Loading in progress...", OnTextChanged));
public string Text
{
get => (string)this.GetValue(TextProperty);
set { this.SetValue(TextProperty, value); }
}
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var c = (PleaseWait) d;
c.Caption.Text = c.Text;
}
答案 1 :(得分:0)
您可以绑定PropertyChangedCallback
的{{1}}而不是像提到的ASh那样使用TextProperty
TextBlock