如何在XAML中访问ViewModel的DependencyProperties?

时间:2012-01-31 14:59:46

标签: c# mvvm wpf-controls

我目前正在编写一个具有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" />

我如何使用我的财产&#34;文件&#34;例如,从ViewModel将它们绑定到MainView中的ListBox的选定项目的XAML中?

Programmaticlly。我可以在我的用户控件的代码隐藏中编写一个方法,但我认为这不是那种美妙的方法。特别是关于MVVM模式的使用。

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

我不太确定你追求的是什么。你的意思是你的ListBox是&#34; Document&#34;的集合。的ViewModels?如果是这样,您可以将UserControl绑定到选定的&#34;文档&#34;用:

<ListBox x:Name="MyListBox" ItemsSource="{Binding MyDocumentCollection}" />

<control:ResultControl x:Name="myControl" DataContext={Binding ElementName="MyListBox", Path="SelectedItem"}/>
编辑:对于MVVM,Serge的答案更好。将所选项目作为ViewModel上的属性。

答案 2 :(得分:0)

您需要将Document属性绑定到viewmodel中的属性:

<control:ResultControl x:Name="myControl" Document="{Binding VmDocument}"/>

在你的ViewModel中:

public MyDocument VmDocument {get;set;}

当然,VmDocument需要在其setter上引发PropertyChanged事件。