自定义用户控件中的绑定问题

Binding issue in custom user control

我创建了一个用户控件,但我无法使绑定工作,我尝试了很多方法但我没有让它工作,值没有显示。

ShowPrice.cs

public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(string), typeof(ShowPrice),
                new FrameworkPropertyMetadata
                (
                    string.Empty,
                    FrameworkPropertyMetadataOptions.Journal |
                    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                    OnValuePropertyChanged
                ));

    public string Value
    {
        get { return (string)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    private static void OnValuePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var showPrice = obj as ShowPrice;
        showPrice?.SetValue(ValueProperty, (string)e.NewValue);
    }

ShowPrice.xaml

<UserControl x:Class="WPF.CustomControls.UserControls.ShowPrice"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         DataContext="{Binding RelativeSource={RelativeSource Self}}">

        <TextBlock Text="{Binding Value}"
                   HorizontalAlignment="Center"
                   Foreground="White"
                   FontSize="40"
                   Margin="5" />

</UserControl>

我的view.xaml

<userControls:ShowPrice Value="{Binding MyViewModelProperty, StringFormat=C2, ConverterCulture='es-AR'}">
</userControls:ShowPrice>

如果我写一个值就可以了

<userControls:ShowPrice Value="Test"/>

不要将 DataContext 绑定到 Self。改为使用 RelativeSource 绑定(但这不是问题所在):

Text="{Binding Value, RelativeSource={RelativeSource AncestorType=UserControl}}"

此外,摆脱你的 OnValuePropertyChanged 处理程序。它在设置 Value 时调用,因此几乎没有必要再次设置 Value (但这也不是问题)。

最后,这可能是你的问题:

Foreground="White"

这个东西是白底用的吗?我保留了您的所有代码,并进行了一处更改:

<TextBlock 
    Text="{Binding Value}"
    Background="YellowGreen"
    HorizontalAlignment="Center"
    Foreground="White"
    FontSize="40"
    Margin="5" 
    />

这个:

    Background="YellowGreen"

我看到黄绿色背景上的白色文字。