2016-12-29 41 views
0

我創建了一個usercontrol,但我無法使綁定工作,我嘗試了很多方法,但我沒有得到它的工作,值不顯示。自定義用戶控件中的綁定問題

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> 

如果我令狀E中的值,如果它的工作原理

<userControls:ShowPrice Value="Test"/> 
+0

它看起來像你的問題是視圖模型沒有綁定到你的視圖,因爲它沒有找到MyViewModel屬性。正如你所說,如果你明確地設置了「Value」,它就可以工作,所以問題不在ShowPrice.xaml中。 –

+1

此外,您不需要「showPrice?.SetValue(ValueProperty,(string)e.NewValue);」 Value屬性設置器是多餘的。 –

回答

1

不綁定DataContextSelf。使用的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" 

,我看到黃綠色的背景白色文本。

+0

感謝這個例子,我的代碼更大,有一個帶有彩色背景的邊框,我只是放了那段代碼,只是錯誤的一部分。通過刪除Self DataContext解決了該問題 – avechuche