我可以连接两个没有依赖属性的视图模型吗?



我有MainWindow(为清楚起见进行了简化(:

<Window>
    <!-- (...) -->
    <Window.DataContext>
         <vm:MainWindowViewModel />
    </Window.DataContext>
    <!-- (...) -->
    <CheckBox IsChecked="{Binding ShowAdvanced}" Content="Advanced view" />
    <uc:MyUserControl DataContext={Binding MyUserControlViewModel} />
</Window>

主窗口视图模型:

public partial class MainWindowViewModel : ViewModelBase
{
    public MainWindowViewModel()
    {
         MyUserControlVM = new MyUserControlViewModel();
    }
    private bool _showAdvanced;
    public bool ShowAdvanced
    {
        get => _showAdvanced;
        set { _showAdvanced = value; NotifyPropertyChanged(); }
    }
    private MyUserControlViewModel _myUserControlVM;
    public MyUserControlViewModel MyUserControlVM
    {
        get => _myUserControlVM;
        set { _myUserControlVM= value; NotifyPropertyChanged(); }
    }
}

在我的用户控件中,我有一些控件应该在未选中"显示高级"复选框时隐藏。

<GroupBox Header="Some advanced stuff"
    Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.(vm:MainWindowViewModel.ShowAdvanced), Converter={StaticResource BoolToVis}}">
    <!-- (...) -->
</GroupBox>

这实际上有效,但我不喜欢这样,因为UserControl依赖于MainWindow。

如何在没有依赖属性的情况下正确连接这些视图模型?

我试图将其添加到MyUserControlViewModel中:

public MyUserControlViewModel(MainWindowViewModel parent)
{
    Parent = parent;
}
private MainWindowViewModel _parent;
public MainWindowViewModel Parent
{
    get { return _parent; }
    set { _parent = value; NotifyPropertyChanged(); }
}

并在其中一个 MyUserControl 控件上绑定可见性,如下所示:

Visibility="{Binding Parent.ShowAdvanced}"

但这不起作用(我的用户控件没有收到通知?

ShowAdvanced 属性添加到控制虚拟机,并在将新值分配给MainViewModel ShowAdvanced属性时将值分配给每个控制虚拟机。

public class MainViewModel : Base.ViewModelBase
{
    private bool _showAdvanced;
    public MainViewModel()
    {
        MyUserControl1 = new MyUserControlViewModel { Message = "Control 1" };
        MyUserControl2 = new MyUserControlViewModel { Message = "Control 2" };
        MyUserControl3 = new MyUserControlViewModel { Message = "Control 3" };
    }
    public bool ShowAdvanced
    {
        get => _showAdvanced;
        set
        {
            this.RaiseAndSetIfChanged( ref _showAdvanced, value );
            MyUserControl1.ShowAdvanced = value;
            MyUserControl2.ShowAdvanced = value;
            MyUserControl3.ShowAdvanced = value;
        }
    }
    public MyUserControlViewModel MyUserControl1 { get; }
    public MyUserControlViewModel MyUserControl2 { get; }
    public MyUserControlViewModel MyUserControl3 { get; }
}
public class MyUserControlViewModel : Base.ViewModelBase
{
    private bool _showAdvanced;
    private string _message;
    public bool ShowAdvanced { get => _showAdvanced; set => this.RaiseAndSetIfChanged( ref _showAdvanced, value ); }
    public string Message { get => _message; set => this.RaiseAndSetIfChanged( ref _message, value ); }
}

相关内容

  • 没有找到相关文章