Reputation: 1560
I created a usercontrol but I can not make the binding work, I tried in many ways but I did not get it to work, the value is not displayed.
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>
My view.xaml
<userControls:ShowPrice Value="{Binding MyViewModelProperty, StringFormat=C2, ConverterCulture='es-AR'}">
</userControls:ShowPrice>
If I write a value if it works
<userControls:ShowPrice Value="Test"/>
Upvotes: 0
Views: 46
Reputation: 37059
Don't bind DataContext
to Self
. Use a RelativeSource binding instead (but this isn't the problem):
Text="{Binding Value, RelativeSource={RelativeSource AncestorType=UserControl}}"
Also, get rid of your OnValuePropertyChanged
handler. It's called when Value
is set, so it's hardly necessary to set Value
again (but that's not the problem either).
Finally, this may be your problem:
Foreground="White"
Is this thing being used on a white background? I kept all of your code exactly as you had it, and made one change:
<TextBlock
Text="{Binding Value}"
Background="YellowGreen"
HorizontalAlignment="Center"
Foreground="White"
FontSize="40"
Margin="5"
/>
This:
Background="YellowGreen"
And I saw white text on a yellow-green background.
Upvotes: 1