gpt4 book ai didi

c# - WPF UserControl 如何继承 WPF UserControl?

转载 作者:IT王子 更新时间:2023-10-29 03:38:25 27 4
gpt4 key购买 nike

以下 WPF UserControl 调用了 DataTypeWholeNumber,它有效。

现在我想创建一个名为 DataTypeDateTimeDataTypeEmail 等的 UserControl

许多依赖属性将由所有这些控件共享,因此我想将它们的通用方法放入 BaseDataType 并让这些 UserControl 中的每一个都继承自该基类型。

但是,当我这样做时,我得到了错误:部分声明可能没有不同的基类

那么我如何实现 UserControls 的继承,以便共享功能都在基类中?

using System.Windows;
using System.Windows.Controls;

namespace TestDependencyProperty827.DataTypes
{
public partial class DataTypeWholeNumber : BaseDataType
{
public DataTypeWholeNumber()
{
InitializeComponent();
DataContext = this;

//defaults
TheWidth = 200;
}

public string TheLabel
{
get
{
return (string)GetValue(TheLabelProperty);
}
set
{
SetValue(TheLabelProperty, value);
}
}

public static readonly DependencyProperty TheLabelProperty =
DependencyProperty.Register("TheLabel", typeof(string), typeof(BaseDataType),
new FrameworkPropertyMetadata());


public string TheContent
{
get
{
return (string)GetValue(TheContentProperty);
}
set
{
SetValue(TheContentProperty, value);
}
}

public static readonly DependencyProperty TheContentProperty =
DependencyProperty.Register("TheContent", typeof(string), typeof(BaseDataType),
new FrameworkPropertyMetadata());


public int TheWidth
{
get
{
return (int)GetValue(TheWidthProperty);
}
set
{
SetValue(TheWidthProperty, value);
}
}

public static readonly DependencyProperty TheWidthProperty =
DependencyProperty.Register("TheWidth", typeof(int), typeof(DataTypeWholeNumber),
new FrameworkPropertyMetadata());



}
}

最佳答案

确保您已将 xaml 中的第一个标记更改为也从您的新基类型继承

所以

<UserControl x:Class="TestDependencyProperty827.DataTypes.DataTypeWholeNumber"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
>

成为

<myTypes:BaseDataType x:Class="TestDependencyProperty827.DataTypes.DataTypeWholeNumber"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:myTypes="clr-namespace:TestDependencyProperty827.DataTypes"
>

因此,总结完整的答案,包括来自以下评论的额外详细信息:

  • 基类不应包含 xaml 文件。在单个(非部分)cs 文件中定义它,并将其定义为直接从 Usercontrol 继承。
  • 确保子类在 cs 代码隐藏文件和 xaml 的第一个标记中都继承自基类(如上所示)。

关于c# - WPF UserControl 如何继承 WPF UserControl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/887519/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com