【问题标题】:In WPF, how can I inherit from ToolBar AND have a XAML file?在 WPF 中,如何从 ToolBar 继承并拥有 XAML 文件?
【发布时间】:2009-09-25 12:48:05
【问题描述】:

我可以通过创建一个普通的 C# 类来继承和增强 ToolBar 类,然后这样做:

public class NiceToolBar : ToolBar
{
    private ToolBarTray mainToolBarTray;

    public NiceToolBar()
    {
        mainToolBarTray = new ToolBarTray();

        mainToolBarTray.IsLocked = true;
        this.Background = new SolidColorBrush(Colors.LightGray);
        ...

但这迫使我像这样操作 代码 中的所有控件:

ToolBar toolBar = new ToolBar();
toolBar.Background = new SolidColorBrush(Colors.Transparent);
toolBar.Cursor = Cursors.Hand;

StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Horizontal;

TextBlock tb = new TextBlock();
tb.Text = label;
tb.Margin = new Thickness { Top = 3, Left = 3, Bottom = 3, Right = 10 };

Image image = new Image();
image.Source = new BitmapImage(new Uri("Images/computer.png", UriKind.Relative));

sp.Children.Add(image);
sp.Children.Add(tb);
toolBar.Items.Add(sp);

我真正需要的是 XAML 来完成这个繁琐的参数分配和布局。

所以我创建了一个新的用户控件,并将后面的代码更改为继承 ToolBar,如下所示:

public partial class SmartToolBar : ToolBar
{
    public SmartToolBar(string label)
    {
        InitializeComponent();

        TheLabel.Text = label;
    }
}

在我的 XAML 中我放了这个:

<UserControl x:Class="TestUserControl.Helpers.SmartToolBar"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Orientation="Horizontal">
        <Image Source="Images/computer.png"/>
        <TextBlock x:Name="TheLabel"/>
    </StackPanel>
</UserControl>

但是当我运行它时,我得到了错误:

部分声明 “TestCallConstructor.Helpers.SmartToolBar” 不能定义不同的基类

我怎样才能让我的用户控制使用 XAML?

【问题讨论】:

    标签: c# wpf xaml user-controls


    【解决方案1】:

    您正在寻找自定义控件(不是 UserControl)。当您编写自定义控件时,您可以指定其默认视图(即 XAML)。

    您可以在 Google 上搜索如何在 WPF 中创建自定义控件,但这是我为您搜索到的一个链接 How to Create a WPF Custom Control

    希望这会有所帮助:)。

    【讨论】:

      【解决方案2】:

      如果您从ToolBar 继承,则您不会编写UserControl,因为ToolBar 不会从UserControl 继承。您的 XAML 将基类指定为 UserControl,而您的 C# 指定 ToolBar。显然那里有冲突。

      我不明白你首先在代码后面做这些事情的前提。为什么不将ToolBarItemsSource 绑定到您的项目集合,并使用通常的ItemsControl 属性来控制呈现?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-07
        • 1970-01-01
        • 2020-03-08
        • 2015-03-28
        • 1970-01-01
        相关资源
        最近更新 更多