Search code examples
wpfuser-controlsdatatemplate

Reference Usercontrol in a DataTemplate from the DataTemplate's datatype class


I have a datatemplate like this:

<DataTemplate DataType="{x:Type mvvm:ComponentViewModel}">
   <v:UCComponents></v:UCComponents>
</DataTemplate> 

UCComponent is a usercontrol with a public property called ID. ComponentViewModel also has a property called ID. I would like to set UCComponent ID property in the setter of the ViewModel's property. How can I do that?

This is what I've tried:

private string _ID;
public string ID 
{
    set { ((UCComponents)((DataTemplate)this).LoadContent()).ID = value; } 
}

Error: this cannot be converted from ComponentViewModel to DataTemplate. Any help will be appreciated.

I'm not keeping true to MVVM design pattern, which is probably the reason for my frustration, but is there a way to access the UserControl used in the template?

Amanda


Thanks for the help, but it doesn't work. The getter and setter of ID is never called. This is my code:

public static DependencyProperty IDProperty = DependencyProperty.Register("ID",     typeof(Guid), typeof(UCComponents));
public Guid ID
{
    get
    { return (Guid)GetValue(IDProperty); }
    set
    { 
        SetValue(IDProperty, value);
        LoadData();
    }
}

I can't make the UserControl a DependencyObject. Is that perhaps the problem?


Solution

  • You can add a dependency property on your user control (UCComponents.xaml.cs) as follows

        public static DependencyProperty IDProperty = DependencyProperty.Register(
        "ID",
        typeof(Object),
        typeof(BindingTestCtrl));
    
        public string ID
        {
            get
            {
                return (string)GetValue(IDProperty);
            }
            set
            {
                SetValue(IDProperty, value);
            }
        }
    

    then you can bind it using

    <DataTemplate DataType="{x:Type mvvm:ComponentViewModel}">
        <v:UCComponents ID="{Binding ID}" />
    </DataTemplate>
    

    Another solution would be to handle the DataContextChanged event on your user control with something like

        private ComponentViewModel _data;
    
        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            _data = e.NewValue as ComponentViewModel;
            this.ID = _data.ID;
        }