简体   繁体   中英

How to set a property of a property in XAML?

I have a user-control as my view (named MyView ) and it has it's data context set to an instance of my view-model (of type MyViewModel ).
I have in my view's code-behind a read-only property for it (which is the MVVM-Light snippet) that looks like so:

public MyViewModel Vm
{
    get { return (MyViewModel) DataContext; }
}

MyViewModel has a property named Title of type string, and I want to change it through XAML because MyView is being used as an ItemTemplate for a ListBox .

<ListBox ItemsSource="{Binding MyViewModelCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Controls:MyView /> <!-- How do I set Vm.Title property here? -->
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

How can I do this?
or perhaps there is a better way?

Could you simply make a property within your MyView that reflects down to the view model?

public string Title 
{ 
    get { return ((MyViewModel) DataContext).Title; } 
    set { ((MyViewModel) DataContext).Title = value; }
}

Then write:

<Controls:MyView Title="MyTitle" />

If you want to bind the title, you'll have to make it a dependency property not a regular property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM