代码之家  ›  专栏  ›  技术社区  ›  bas

从ParentViewModel到子用户控件的WPF绑定不工作

  •  0
  • bas  · 技术社区  · 5 年前

    忽略了代码片段中不相关的内容(比如私有成员声明)

    视图模型:

    public class LinearGaugeViewModel<T> : INotifyPropertyChanged where T : GaugeElementViewModel
    {
        public double Value
        {
            get => _value;
            set
            {
                _value = value;
                OnPropertyChanged();
            }
        }
    }
    

    “父”用户控件的XAML:

    <ItemsControl ItemsSource="{Binding Elements}">
        <ItemsControl.Resources>
            <DataTemplate DataType="{x:Type local:HorizontalGaugeElementViewModel}">
                <local:HorizontalGaugeElement Value="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DataContext.Value, Mode=OneWay}"/>
            </DataTemplate>
        </ItemsControl.Resources>
    </ItemsControl>
    

    public static DependencyProperty ValueProperty = DependencyProperty.Register(
        nameof(Value),
        typeof(double),
        typeof(HorizontalGaugeElement));
    
    public double Value
    {
        get => (double) GetValue(ValueProperty);
        set => SetValue(ValueProperty, value);
    }
    

    我想要 Value LinearGaugeViewModel HorizontalGaugeElement .

    当我更改值时,我可以看到setter LinearGaugeViewModel.Value

    public event PropertyChangedEventHandler PropertyChanged;
    
    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    

    仍然是的,dependency属性中的设置从未设置。

    我做错什么了?

    0 回复  |  直到 5 年前
        1
  •  2
  •   ASh aminescm    5 年前

    property changed callback

    如果回调触发,那么您关于“依赖项属性中的设置永远不会被设置”的假设是不正确的。

    WPF用途 DependencyObject.SetValue(ValueProperty) public double Value )未使用