c# - 未调用 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;
}
}
}
解决方案
肯定有类似的东西
<UserControl.DataContext>
<local:MatrixViewModel/>
</UserControl.DataContext>
在 UserControl 的 XAML 中。删除它,因为它可以防止像
<controls:MatrixView Matrix="{Binding Matrix}" />
在正确的视图模型实例中查找 Matrix 属性,即从 MainWindow 继承的那个。
具有可绑定(即依赖)属性的用户控件永远不应设置自己的 DataContext,因为这样做会破坏这些属性的任何基于 DataContext 的绑定。
推荐阅读
- javascript - 将参数传递给视图中的操作
- javascript - 如何在不使用 setTimeout() 的情况下使代码在 x 时间后执行
- python - 角色可以有不同的属性吗?(烧瓶 SQLAlchemy)
- node.js - 如何使 MongoClient 在 node js rest API 的所有页面中全局可用
- javascript - codeandbox.io 无法读取 null 的属性“addEventListener”
- offset - TimeScaleDB 连续聚合刷新策略结束偏移未按预期工作
- python - 循环中数据框的嵌套动态变量
- excel - 命令栏“工作簿选项卡”如何自动选择
- ruby-on-rails - 无法使用 yarn + webpacker + Ruby on Rails 6 获取包
- sql - SQL - 如何检查所有可用日期是否存在数据?