WPF UserControl с общим кодом - PullRequest
       2

WPF UserControl с общим кодом

12 голосов
/ 28 сентября 2010

У меня есть этот код:

CustomUserControl.xaml.cs

namespace MyProject
{
    public partial class CustomUserControl<T> : UserControl
    {
        ...
    }
}

и этот xaml:

CustomUserControl.xaml

<UserControl x:Class="MyProject.CustomUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Grid>

</Grid>

Не работает, так как x: Class = "MyProject.CustomUserControl" не соответствует определению универсального класса выделенного кода.Есть ли способ заставить эту работу?

Ответы [ 3 ]

11 голосов
/ 10 июня 2013

Вы можете создать общий файл с выделенным кодом без XAML-файла:

public class CustomUserControl<T>: UserControl
{ }

и чем он является производным от конкретного класса в качестве параметра:

public partial class SpecificUserControl : CustomUserControl<Presenter>
{
    public SpecificUserControl()
    {
        InitializeComponent();
    }
}

XAML:

<application:CustomUserControl 
     x:TypeArguments="application:Presenter"
     xmlns:application="clr-namespace:YourApplicationNamespace"
...

К сожалению, похоже, что дизайнер Visual Studio не поддерживает такие обобщенные варианты, пока Visual Studio 2012 Update 2 (см. https://stackoverflow.com/a/15110115/355438)

5 голосов
/ 20 января 2016

До сих пор не нашел моего решения нигде.Основное отличие состоит в том, что у меня есть один файл .xaml для общего пользовательского класса управления, а не один для каждого фактического пользовательского элемента управления.

GenericUserControl.xaml.cs

using System.Windows.Controls;

namespace TestGenericUserControl
{
    public abstract partial class GenericUserControl : UserControl
    {
        // If you use event handlers in GenericUserControl.xaml, you have to define 
        // them here as abstract and implement them in the generic class below, e.g.:

        // abstract protected void MouseClick(object sender, MouseButtonEventArgs e);
    }

    public class GenericUserControl<T> : GenericUserControl
    {
        // generic properties and stuff

        public GenericUserControl()
        {
            InitializeComponent();
        }
    }

    // To use the GenericUserControl<T> in XAML, you could define:
    public class GenericUserControlString : GenericUserControl<string> { }
    // and use it in XAML, e.g.:
    // <GenericUserControlString />
    // alternatively you could probably (not sure) define a markup extension to instantiate
    // it directly in XAML
}

GenericUserControl.xaml

<UserControl x:Class="TestGenericUserControl.GenericUserControl"
        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">
    <Grid>
        <Label Content="hello" />
    </Grid>
</UserControl>
3 голосов
/ 18 октября 2010

К сожалению, XAML не поддерживает общий код, вы можете обойти это.

См. Ссылки ниже:

http://forums.silverlight.net/forums/p/29051/197576.aspx

Могу ли я указатьуниверсальный тип в XAML (до .NET 4 Framework)?

Может быть, универсальные элементы управления будут изначально поддерживаться в будущих версиях Visual Studuo с XAML 2009.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...