Pyth0n
Pyth0n

Reputation: 367

How can I access the DependencyProperties of my ViewModel in XAML?

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.

Upvotes: 2

Views: 352

Answers (3)

Louis Kottmann
Louis Kottmann

Reputation: 16628

You need to bind the Document property to a property in your viewmodel:

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

And in your ViewModel:

public MyDocument VmDocument {get;set;}

Of course, VmDocument needs to raise the PropertyChanged event on its setter.

Upvotes: 0

GazTheDestroyer
GazTheDestroyer

Reputation: 21241

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:

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

<control:ResultControl x:Name="myControl" DataContext={Binding ElementName="MyListBox", Path="SelectedItem"}/>

EDIT: Serge's answer is better with regards to MVVM. Having the selected item as a property on your ViewModel.

Upvotes: 0

Assuming that MainViewModel class have Documents and Document (i.e. current document) properties, the XAML should look like:

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

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

Upvotes: 1

Related Questions