【发布时间】:2016-12-29 18:55:17
【问题描述】:
我创建了一个用户控件,但我无法使绑定工作,我尝试了很多方法但我没有让它工作,值不显示。
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"/>
【问题讨论】:
-
看起来你的问题是视图模型没有绑定到你的视图,因为它没有找到 MyViewModelproperty。正如您所说,如果您明确设置“值”,它会起作用,所以问题不在 ShowPrice.xaml 中。
-
另外,您不需要“showPrice?.SetValue(ValueProperty, (string)e.NewValue);”行它是 Value 属性设置器的多余部分。
标签: c# wpf xaml user-controls