如何在 XAML 中访问 ViewModel 的 DependencyProperties?
我目前正在使用 MVVM 模式编写一个用户控件,它具有一些属性,例如 Document。
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 中绑定到列表框中的选定项目例如主视图?
以编程方式。我可以在用户控件的代码隐藏中编写一个方法,但我认为这不是最好的方法。尤其是关于MVVM模式的使用。
I am currently writing a user control with the MVVM pattern which has some Properties, e.g. Document.
DependencyProperty in the ViewModel
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 which use the User Control
<control:ResultControl x:Name="myControl" />
How can I use my property "Document" from the ViewModel to bind them in XAML against the selected item of a ListBox in the MainView for example?
Programmaticlly. I can write a method in the code-behind of my user control, but this is I think not the beautiful way to do that. Especially with regard to the use of MVVM pattern.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设 MainViewModel 类具有 Documents 和 Document(即当前文档)属性,则 XAML 应如下所示:
Assuming that MainViewModel class have Documents and Document (i.e. current document) properties, the XAML should look like:
我不太确定你在追求什么。您的意思是您的列表框是“文档”ViewModel 的集合吗?如果是这样,您可以将 UserControl 绑定到选定的“文档”:
编辑:Serge 的答案对于 MVVM 更好。将所选项目作为 ViewModel 的属性。
I'm not quite sure what you're after. Do you mean your ListBox is a collection of "Document" ViewModels? If so you can bind your UserControl to the selected "Document" with:
EDIT: Serge's answer is better with regards to MVVM. Having the selected item as a property on your ViewModel.
您需要将 Document 属性绑定到视图模型中的属性:
在您的 ViewModel 中:
当然,VmDocument 需要在其设置器上引发 PropertyChanged 事件。
You need to bind the Document property to a property in your viewmodel:
And in your ViewModel:
Of course, VmDocument needs to raise the PropertyChanged event on its setter.