我目前正在使用具有某些属性的MVVM模式编写用户控件,例如文档。

ViewModel 中的 DependencyProperty

public static readonly DependencyProperty DocumentProperty = DependencyProperty.Register("Document", typeof(MyDocument), typeof(ResultControlViewModel), new PropertyMetadata(OnDocumentChanged));

        public MyDocument Document
        {
            get { return (MyDocument)GetValue(DocumentProperty); }
            set { SetValue(DocumentProperty, value); }
        }

使用用户控件的MainView
<control:ResultControl x:Name="myControl" />

例如,如何使用ViewModel中的属性“Document”将它们在XAML中与MainView中ListBox的选定项目绑定(bind)?

以编程方式。我可以在用户控件的代码后面编写一个方法,但是我认为这不是实现此目的的好方法。特别是关于MVVM模式的使用。

最佳答案

假设MainViewModel类具有Documents和Document(即当前文档)属性,则XAML应该如下所示:

<ListBox ItemsSource={Binding Path=Documents}, SelectedItem={Binding Path=Document}>
...
</ListBox>

<control:ResultControl DataContext={Binding Path=Document, Mode=OneWay} />

关于c# - 如何在XAML中访问ViewModel的DependencyProperties?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9081719/

10-13 06:21