简体   繁体   中英

In WPF, how can I inherit from ToolBar AND have a XAML file?

I can inherit and enhance the ToolBar class by creating a plain C# class, then doing this:

public class NiceToolBar : ToolBar
{
    private ToolBarTray mainToolBarTray;

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

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

But this forces me to manipulate all my controls in code like this:

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);

What I really need is XAML to do this tedious parameter assigning and layout.

So I create a new User Control and change the code behind to inherit ToolBar like this:

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

        TheLabel.Text = label;
    }
}

And in my XAML I put this:

<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>

But when I run it, I get the error:

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

How can I have my user control with XAML?

You're not writing a UserControl if you're inheriting from ToolBar , since ToolBar does not inherit from UserControl . Your XAML is specifying the base class as UserControl whilst your C# is specifying ToolBar . Obviously there is a conflict there.

I don't understand your premise for doing this stuff in code behind in the first place. Why not just bind your ToolBar 's ItemsSource to your collection of items, and use the usual ItemsControl properties to control the rendering?

You are looking for Custom Controls (not UserControl). When you write a custom control you can specify its default view (ie XAML).

You can google how to create custom controls in WPF, but here is one link I googled out for you How to Create a WPF Custom Control .

Hope this helps :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM