首页 > 解决方案 > 未调用 WPF DependencyProperty PropertyChangedCallback

问题描述

我的问题是我的OnMatrixPropertyChanged方法永远不会被调用。绑定到同一属性的标签确实会更新,因此我知道绑定正在发生在 Matrix 属性上。

我有一个UserControl我想添加DependencyProperty到的,以便可以绑定到它。我的主窗口如下所示:

<Window.DataContext>
    <local:MainWindowViewModel />
</Window.DataContext>

<StackPanel>
    <Button
        Command="{Binding LoadMatrixCommand}"
        Content="Load"
        Width="150">
    </Button>

    <Label
        Content="{Binding Matrix.Title}">
    </Label>

    <controls:MatrixView
        Matrix="{Binding Path=Matrix, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    </controls:MatrixView>
</StackPanel>

在我的MatrixView UserControl代码隐藏中,我有这样的DependencyProperty集合:

public partial class MatrixView : UserControl
{
    public static readonly DependencyProperty MatrixProperty =
        DependencyProperty.Register(nameof(Matrix), typeof(Matrix), typeof(MatrixView), new PropertyMetadata(default(Matrix), OnMatrixPropertyChanged));

    private static void OnMatrixPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // Do Something
    }

    public Matrix Matrix
    {
        get => (Matrix)GetValue(MatrixProperty);
        set => SetValue(MatrixProperty, value);
    }

    public MatrixView()
    {
        InitializeComponent();
    }
}

我一定错过了一些非常明显的东西......

编辑#1:查看模型

public class MatrixViewModel : ViewModelBase
{
    public MatrixViewModel()
    {
    }
}

public class MainWindowViewModel : ViewModelBase
{
    private IMatrixService _matrixService;
    private Matrix _matrix;

    public Matrix Matrix
    {
        get => _matrix;
        set
        {
            _matrix = value;
            base.RaisePropertyChanged();
        }
    }

    public ICommand LoadMatrixCommand { get; private set; }

    public MainWindowViewModel()
    {
        LoadMatrixCommand = new RelayCommand(LoadMatrix);
        _matrixService = new MatrixService();
    }

    private void LoadMatrix()
    {
        var matrixResult = _matrixService.Get(1);

        if (matrixResult.Ok)
        {
            Matrix = matrixResult.Value;
        }
    }
}

标签: c#wpfxamldata-bindingdependency-properties

解决方案


肯定有类似的东西

<UserControl.DataContext>
    <local:MatrixViewModel/>
</UserControl.DataContext>

在 UserControl 的 XAML 中。删除它,因为它可以防止像

<controls:MatrixView Matrix="{Binding Matrix}" />

在正确的视图模型实例中查找 Matrix 属性,即从 MainWindow 继承的那个。

具有可绑定(即依赖)属性的用户控件永远不应设置自己的 DataContext,因为这样做会破坏这些属性的任何基于 DataContext 的绑定。


推荐阅读