2010-09-28 33 views
9

我背後有這樣的代碼:WPF用戶控件與通用的代碼隱藏

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」與代碼隱藏的泛型類定義不匹配。有什麼方法可以使這項工作?

回答

8

您可以創建通用的「支持代碼隱藏「文件,不帶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更新2(請參閱https://stackoverflow.com/a/15110115/355438

4

到目前爲止,還沒有找到我的解決方案。 主要區別在於,我爲通用用戶控件類獲得了一個.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> 
+0

我有種看到你在做什麼,但我不是在XAML結構是最好的。 您如何/在哪裏指定控件的外觀?我已將所有代碼複製到測試項目中,但我無法:定義它應該是什麼樣子,如何在MainWindow.xaml中使用此「UserControl」,以及如何將數據綁定到它,例如,將'MyGeneric(Of T)'綁定到'Label'的'Content'。 – 2017-05-08 14:07:29

+0

@Zach我爲你寫了一個小例子。看看[this](https://github.com/timmi-on-rails/GenericUserControlWPF)。 – Tom 2017-05-09 20:54:58

相關問題