简体   繁体   中英

How can I display view inside content control in wpf

FirstView.xaml contains Something like this

<ContentControl Name="ContentControlName" Grid.Row="1" Grid.Column="0" Content="{Binding SelectionViewModel}"/>

My SelectionView.xaml contains

<TextBox x:Name="textBoxName" Text="{Binding Name}"/>
<TextBox IsReadOnly="True" Text="{Binding Uid}"/>

In the FirstViewModel I have created a property like below

private SelectionViewModel selectionViewModel;
public SelectionViewModel SelectionViewModel
{
    get
    {
        return this.selectionViewModel;
    }
}

Content control with two text box is not displayed when I run

Is the way done right?

Since you used binding, you need raise up PropertyChanged event. Your ViewModel class (SelectionViewModel) must implement INotifyPropertyChanged .

public class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private SelectionViewModel selectionViewModel;

    public SelectionViewModel SelectionViewModel
    {
        get
        {
            return this.selectionViewModel;
        }
        private set
        {
            this.selectionViewModel = value;
            PropertyChanged?.Invoke(this, nameof(SelectionViewModel));
        }
    }
}

You passed SelectionViewModel instance to Content property of ContentControl. Your ContentControl must have special datatemplate coupled with this view model. Otherwise, it will not work.

For example:

<ContentControl Content="{Binding SelectionViewModel}">
    <ContentControl.ContentTemplate>
        <DataTemplate DataType="{x:Type local:SelectionViewModel}">
            <!-- Here is your template -->
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

Also you shouldn't use same names for type SelectionViewModel and property SelectionViewModel.

Since you wasn't provide a source code we can't figure out the exact cause of your error. I hope it was helpful for you.

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