2016-12-29 4 views
0

私はユーザーコントロールを作成しましたが、バインディング作業を行うことはできません。さまざまな方法で試しましたが、機能しない場合、値は表示されません。カスタムユーザーコントロールでのバインドの問題

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

MyViewModelプロパティが見つからないため、ビューモデルがビューにバインドされていないことが問題のようです。あなたが言うように、 "値"を明示的に設定すると、それは機能しますので、問題はShowPrice.xamlにありません。 –

+1

また、 "showPrice?.SetValue(ValueProperty、(string)e.NewValue);"という行は必要ありません。これは、Valueプロパティ設定の冗長性です。 –

答えて

1

を動作するかどうE値はSelfDataContextをバインドしないでください。代わりに、バインディングRelativeSource(しかし、これは問題ではありません)を使用します。また

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

を、あなたのOnValuePropertyChangedハンドラを取り除きます。 Valueが設定されているときに呼び出されるため、Valueを再度設定する必要はほとんどありません(しかし、どちらでも問題はありません)。

最後に、これはあなたの問題になることがあります。

Foreground="White" 

は白地に使用されているこの事ですか?私はあなたがそれを持っていたとおりに、あなたのコードのすべてを保持し、1つの変更を行った:

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

この:

Background="YellowGreen" 

そして私は黄緑色の背景に白のテキストを見ました。

+0

例のおかげで、私のコードはより大きく、色のついた背景のボーダーがあります。ちょうどその部分をエラーの一部に置きました。この問題は、Self DataContext – avechuche

関連する問題