简体   繁体   中英

How to access this user control in Main Window

I have one user control in my WPF app

 <UserControl x:Class="NewWPFApp.ProgressControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <Expander Header="{Binding Path=Headerval}">
        <StackPanel Margin="10,4,0,0">
            <DataGrid
            x:Name="dataGrid"
            AutoGenerateColumns="False"
           ItemsSource="{Binding Path=records}"/>
        </StackPanel>
    </Expander>
</Grid>

and in my Mainwindow when I am doing this

<Window xmlns:NewWPFApp="clr-namespace:NewWPFApp"  x:Class="NewWPFApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>

    <ListBox x:Name="peopleListBox" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Background="AliceBlue">
                    <NewWPFApp:ProgressControl Height="100" Width="100"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>
</Grid>

I cant see the output. If I remove it from the Data template then it works.But not inside the data template.

What am I missing ???

Thanks

ListBox.ItemTemplate specifies how items added to a list box will be displayed. In your case, you uses your own custom control. However, at the same time you added no items to the list box so there is nothing to display. To populate the list box you can use binding eg:

<ListBox ItemsSource="{Binding ItemsToBeDisplayed}" x:Name="peopleListBox" >
    ...
</ListBox>

Where ItemsToBeDisplayed is a property of a view model (if you use MVVM pattern) that returns a collection of objects. If not you can populate ItemsSource without using binding:

var list = new List<People>();
//Add objects to a list
peopleListBox.ItemsSource = list;

I assumed that you have People class that models people you want to display in your application. People class should have Headerval and records properties because you use them in your your ProgressControl control. If you do as described, a new instance of your ProgressControl control will be created for every object in ItemsSource .

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