XAML 无法使我的DependencyProperty按预期工作[重复]

dfddblmv  于 2023-11-14  发布在  其他
关注(0)|答案(2)|浏览(102)

此问题在此处已有答案

Callback when dependency property receives xaml change(2个答案)
4年前关闭。
我有一个非常简单的用户控件,它显示一个等待动画,上面有一个文本:

<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"/>


我的问题是,它仍然显示“Loading...”而不是“Jegg Robot”,尽管我的Departments属性:

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);
        }
    }
}


我错过了什么?

g6baxovj

g6baxovj1#

WPF不使用DP(public string Text)的公共属性 Package 器,当从xaml(<controls:PleaseWait Text="Jegg Robot"/>)设置属性时,它直接使用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;
}

字符串

cczfrluj

cczfrluj2#

您可以将TextBlockTextProperty绑定到PropertyChangedCallback,而不是像前面提到的ASh那样使用PropertyChangedCallback

...
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"
    Grid.Row="0" FontSize="18" Foreground="Black"
    Margin="8" x:Name="Caption" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:PleaseWait}}}"/>
...

字符串

相关问题