【发布时间】:2020-12-29 23:20:57
【问题描述】:
我有一个名为ChartControl 的用户控件,它显示一个图表。要确定ChartControl 是否已初始化,它需要运行在名为DiagnosisViewModel 的ViewModel 中定义的命令。命令在这个 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,但我找不到,我在这里做错了什么
【问题讨论】:
-
我没有看到任何你实例化 VM 或 ReadyCommand 的地方。 VM 与您的问题无关,但 ReadyCommand 未在任何地方创建
标签: c# wpf binding command dependency-properties