我創建了一個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"/>
它看起來像你的問題是視圖模型沒有綁定到你的視圖,因爲它沒有找到MyViewModel屬性。正如你所說,如果你明確地設置了「Value」,它就可以工作,所以問題不在ShowPrice.xaml中。 –
此外,您不需要「showPrice?.SetValue(ValueProperty,(string)e.NewValue);」 Value屬性設置器是多餘的。 –