且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF MVVM-将UserControls上的属性绑定到容器的ViewModel

更新时间:2022-01-23 02:29:27

MyUserControls从MainWindow继承了DataContext,这就是为什么它可以开始使用的原因.当MyUserControl1获得自己的ViewModel时,将成为其DataContext.也许这对您很清楚:)要在绑定中使用MainWindow的DataContext,可以使用RelativeSource或命名Window并使用ElementName

The MyUserControls inherited the DataContext from MainWindow and that's why it works to begin with. When MyUserControl1 get a ViewModel of its own that will be its DataContext. Maybe this was clear to you :) To use the DataContext of the MainWindow in the binding instead you can use RelativeSource or name the Window and use ElementName

<local:MyUserControl Visibility="{Binding ElementName=mainWindow, 
                                          Path=DataContext.MyUserControl1Visibility,
                                          Mode=OneWay,
                                          UpdateSourceTrigger=PropertyChanged}" />