简体   繁体   中英

How to use a User Control XAML within a Class Library

I have a sub project wich is a class and contains DataLib.cs and an user controll MediumTile.xaml. This user control will be the generated to an image to use it as tile background. But before I have to change a few thing dynamicly. So how can I get controll above the LayoutRoot inside MediumTile.xaml for example to set the background color?

Something like this:

MediumTile.LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255, 206, 23, 23);

I've never done it for windows phone 8 , but for normal desktop applications, you can do it by adding the following references:

  • PresentationCore
  • PresentationFramework
  • WindowsBase

Then you can create and access a Control in a normal way.

MediumTile.xaml probably exists in some kind of namespace.

You can find the namespace of the UserControl in the top of the file beside the x:Class declaration.

Typically it'll look something like

x:Class="MyProject.UserControls.MediumTile" 

if your project is set up normally.

If you look at the MediumTile.xaml.cs , you should see a namespace like so

namespace MyProject.UserControls
{
    public partial class MediumTile : UserControl
    ...

First off, you will need to reference your subproject.

Assuming you have a project structure like so...

CurrentProject/
    -MyPage.xaml

SubProject/
    -MediumTile.xaml

Right-click your Solution in Visual Studio and click Properties .

Under Properties select Project Dependencies .

Choose the CurrentProject in the dropdown.

In the Depends On checkbox field, choose the SubProject.

Click on StartUp Project in the side bar.

Make sure Single StartUp Project points to CurrentProject. If not, set it.

Now you're done setting up, you'll need to actually use MediumTile.xaml now.


  1. To use the MediumTile UserControl in another XAML file, you will need to declare

    xmlns:customControls="clr-namespace:MyProject.UserControls"

inside the page header, and call

<ListBox.ItemTemplate>
    <DataTemplate>
        <customControls:MediumTile/>
...
  1. To use this UserControl in another CS file, you will need to import the namespace

    using MyProject.UserControls;

at the top of the page, and reference your control like so (depending on your usercontrol's constructor),

MediumTile mediumTile = new MediumTile()

About your LayoutRoot problem, you can simply set the Background color directly on the UserControl. UserControl inherits from Control, which has the Background property already.

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