将 UserControls Dependency属性 绑定到 ViewModels 属性

Binding UserControls DependencyProperty to ViewModels Property

我有一个名为 ChartControl 的用户控件,它显示一个图表。要确定 ChartControl 是否已初始化,它需要 运行 一个在名为 DiagnosisViewModel 的 ViewModel 中定义的命令。 Command 在这个 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 的 getter 似乎从来没有被调用过,所以我认为我在这里的绑定有任何问题。我尝试了多种模式和 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 事件不同,回调总是在 设置 属性 之后调用。