私はユーザーコントロールを作成しましたが、バインディング作業を行うことはできません。さまざまな方法で試しましたが、機能しない場合、値は表示されません。カスタムユーザーコントロールでのバインドの問題
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"/>
MyViewModelプロパティが見つからないため、ビューモデルがビューにバインドされていないことが問題のようです。あなたが言うように、 "値"を明示的に設定すると、それは機能しますので、問題はShowPrice.xamlにありません。 –
また、 "showPrice?.SetValue(ValueProperty、(string)e.NewValue);"という行は必要ありません。これは、Valueプロパティ設定の冗長性です。 –