将UserControls DependencyProperty绑定到ViewModels属性

问题描述

我有一个名为ChartControl的UserControl,它显示一个图表。为了确定ChartControl已初始化,它需要运行在名为Diagnosisviewmodelviewmodel中定义的命令。命令在此viewmodel中实例化。加载ChartControl之后,它应该执行Command,但是此时它仍然为null。似乎该命令的绑定不能按预期方式工作。让我们用代码更好地解释它:

ChartControl.xaml

<UserControl x:Class="GoBeyond.Ui.Controls.Charts.ChartControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             x:Name="ThisChartControl"
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
</UserControl>

ChartControl.xaml.cs

public partial class ChartControl : INotifyPropertyChanged
{
    public ChartControl()
    {
        Loaded += OnLoaded;
    }

    public static readonly DependencyProperty ReadyCommandProperty = DependencyProperty.Register(
            nameof(ReadyCommand),typeof(ICommand),typeof(ChartControl),new PropertyMetadata((o,args) =>
            {
                Debug.WriteLine("Ready Command updated");
            }));

    public ICommand ReadyCommand
    {
        get { return (ICommand)GetValue(ReadyCommandProperty); }
        set { SetValue(ReadyCommandProperty,value); }
    }

    private void OnLoaded(object sender,RoutedEventArgs e)
    {
        // Initialize the ChartControl with some values
        ...

        // At this point the Command is ALWAYS null
        ReadyCommand?.Execute(this);
    }
}

ChartControl defined in DiagnosisView.xaml

<charts:ChartControl ReadyCommand="{Binding FrequencyReadyCommand}" />

Diagnosisviewmodel

public class Diagnosisviewmodel : viewmodelBase // viewmodelBase derives from Prisms BindableBase
{
    public Diagnosisviewmodel(...)
    {
        FrequencyReadyCommand = new DelegateCommand<ChartControl>(OnFrequencyChartReady);
    }

    public ICommand FrequencyReadyCommand
    {
        get => _frequencyReadyCommand;
        set => SetProperty(ref _frequencyReadyCommand,value);
    }
}

FrequencyReadyCommand的吸气剂似乎从未被调用过,因此我认为此处的绑定存在任何问题。我尝试了多种模式和UpdateSourceTriggers,但我找不到在这里做错的事

解决方法

您应该在依赖项属性回调中调用命令,而不要处理Loaded事件:

public static readonly DependencyProperty ReadyCommandProperty = DependencyProperty.Register(
        nameof(ReadyCommand),typeof(ICommand),typeof(ChartControl),new PropertyMetadata((o,args) =>
        {
            ChartControl chartControl = (ChartControl)o;
            chartControl.ReadyCommand?.Execute(null);
        }));

Loaded事件不同,回调总是在设置属性后 调用。