Search code examples
c#mvvmdata-bindinguwpdatatemplate

DataTemplate with textbox for search


I uses MasterDetailsView control. It has MasterHeaderTemplate property. I want to add a TextBox in order to implementation of items search. I don't understand how to do this. Because DataTemplate don't has a needed property. It's UWP app, don't WPF.

TextBlock got value by MasterHeader property. But how do other binding. For example, placeholder text, event handlers.

MasterHeader="{x:Bind ViewModel.Title}"
MasterHeaderTemplate="{StaticResource MasterHeaderTemplate}"

<DataTemplate
    x:Key="MasterHeaderTemplate">
    <StackPanel>
        <TextBlock
            Text="{Binding}"
            Style="{StaticResource HeaderStyle}" />
        <TextBox
            PlaceholderText="{???}" />
    </StackPanel>
</DataTemplate>

enter image description here


Solution

  • You can use the Binding.ElementName property to set the name of your MasterDetailsView to use as the binding source for the Binding. Then you can access its DataContext(e.g. your ViewModel) and bind the property from ViewModel with PlaceholderText. For example:

    .xaml:

    <Page.Resources>
        <DataTemplate x:Key="MasterHeaderTemplate">
            <StackPanel>
                <TextBlock
            Text="{Binding}" />
                <TextBox PlaceholderText="{Binding ElementName=MyDetailView,Path=DataContext.PlaceholderText}"/>
            </StackPanel>
        </DataTemplate>
    </Page.Resources>
    
    <Grid>
        <controls:MasterDetailsView
          ItemsSource="{Binding Lists}"
          x:Name="MyDetailView" MasterHeader="{Binding Title}" MasterHeaderTemplate="{StaticResource MasterHeaderTemplate}">
            <controls:MasterDetailsView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"></TextBlock>
                </DataTemplate>
            </controls:MasterDetailsView.ItemTemplate>
        </controls:MasterDetailsView>
    </Grid>
    

    .cs:

    public MainPage()
    {
        this.InitializeComponent();
        ViewModel = new MyViewModel();
        ViewModel.Title = "Header";
        ViewModel.PlaceholderText = "MyPlaceholderText";
    
        this.DataContext = ViewModel;
    }
    private MyViewModel ViewModel { get; set; }