简体   繁体   中英

Access bound variables that come from parent user control

I have a parent user control which holds another one called TrainDetailsControl . The data context of the parent user control is set to a ViewModel class (see below).

<UserControl>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ListBox ItemsSource="{Binding Trains}"
                 SelectedItem="{Binding SelectedTrain}"
                 DisplayMemberPath="Name"/>
        <local:TrainDetailsControl Grid.Column="1" DataContext="{Binding SelectedTrain}"/>
    </Grid>
</UserControl>

What I do is "pass" the selected train in the list box to the TrainDetailsControls . Inside that user control I show the details of the selected train object.

<UserControl>
    <StackPanel>
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding Details}"/>
    </StackPanel>
</UserControl>

This is the ViewModel with the shared variables (this is not the complete code, just to give you an idea).

public class TrainViewModel : ViewModelBase
{
    public ObservableCollection<Train> Trains { get; }
        = new ObservableCollection<Train>();

    private Train selectedTrain;
    public Train SelectedTrain
    {
        get { return selectedTrain; }
        set { SetValue(ref selectedTrain, value); }
    }
}

This works well, as when I select a train item from the list box, its details are shown correctly in the other user control. But I'm wondering if it is possible to access Name and Details variables from code-behind in TrainDetailsControl . Would the data context of this last user control be the same as the data context of its parent user control (ie the view model class)?

But I'm wondering if it is possible to access Name and Details variables from code-behind in TrainDetailsControl

Sure. Just cast the DataContext to Train once the view has been loaded:

public partial class TrainDetailsControl : UserControl
{
    public TrainDetailsControl()
    {
        InitializeComponent();
        Loaded += (s, e) =>
        {
            Train selectedTrain = DataContext as Train;
            if (selectedTrain != null)
            {
                //...
            }
        };
    }
}

Would the data context of this last user control be the same as the data context of its parent user control (ie the view model class)?

No, it would the object that SelectedTrain returns since you have bound the DataContext property to this source property. If you don't explicitly set the DataContext property, the DataContext would be inherited from the parent UserControl though.

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