【问题标题】:Binding issue in custom user control自定义用户控件中的绑定问题
【发布时间】: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


【解决方案1】:

不要将DataContext 绑定到Self。改用 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"

我看到黄绿色背景上的白色文字。

【讨论】:

  • 感谢示例,我的代码比较大,有一个带彩色背景的边框,我只是放了那段代码,只是错误的一部分。通过删除 Self DataContext 解决了问题
猜你喜欢
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多