c# - 在 WPF 中,如何从 ToolBar 继承并拥有 XAML 文件?

标签 c# wpf xaml user-controls

我可以通过创建一个普通的 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>

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

Partial declaration of "TestCallConstructor.Helpers.SmartToolBar" may not define different basis classes

如何让我的用户使用 XAML 进行控制?

最佳答案

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

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

希望这有帮助:)。

关于c# - 在 WPF 中,如何从 ToolBar 继承并拥有 XAML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1477102/

相关文章:

c# - WPF 单击 ListBoxItem 内的控件不选择 ListBoxItem

C#,将字符串变量转换为类变量

c# - Lambda,从嵌套列表中获取属性

c# - Xaml 中的 TreeViewItem MVVM IsSelected 不会将值发送到 View 模型

c# - 以编程方式将 AutomationIds 分配给 WPF 中的模板化控件

silverlight - 是否可以在 Silverlight 中选择性地为标签着色?

.net - 从 DataTemplate 访问父 DataContext

c# - 如何使用 CLR 为 .NET 编写另一个调试器

c# - 比较一个字符串到多个字符串

c# - WPF,未选中时隐藏文本框