Search code examples
c#wpfxamlribbon

Is it possible to put a Ribbon or RibbonTab in seperate xaml file?


Repo: https://github.com/babakin34/ribbontest1/

I have a Main.xaml and a MyRibbon.xaml.

MyRibbon.xaml

<ribbon:Ribbon xmlns:ribbon="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <ribbon:RibbonTab Header="">
        <ribbon:RibbonMenuButton Label="Upload"/>
    </ribbon:RibbonTab>
</ribbon:Ribbon>

MyRibbon.xaml.cs

public class MyRibbon : Ribbon {}

Main.xaml

<Grid>
    <MyRibbon/>
</Grid>

The problem is that an empty Ribbon is shown in Grid. (The upload menu is misisng)

Here is the whole project snapshot:

enter image description here


Solution

  • There is no automatic connection between your MyRibbon class and the MyRibbon.xaml file.

    If you want to create custom control you should define a template for it:

    public class MyRibbon : Ribbon {}
    

    <Grid xmlns:ribbon="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
        <Grid.Resources>
            <Style TargetType="local:MyRibbon">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="local:MyRibbon">
                            <ribbon:Ribbon>
                                <ribbon:RibbonTab Header="">
                                    <ribbon:RibbonMenuButton Label="Upload"/>
                                </ribbon:RibbonTab>
                            </ribbon:Ribbon>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Grid.Resources>
        <local:MyRibbon/>
    </Grid>
    

    The other option would be to simply create a UserControl called MyRibbon and put your XAML markup in the MyRibbon.xaml file. You can then use the UserControl like this:

    <local:MyRibbon />
    
    1. Create a new UserControl (Project->Add New Item->User Control (WPF) and name it "MyRibbon".

    2. Replace the contents of the MyRibbon.xaml file with the following:

      <Ribbon x:Class="WpfApplication3.MyRibbon"
                       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
          <RibbonTab Header="">
              <RibbonMenuButton Label="Upload"/>
          </RibbonTab>
      </Ribbon>
      
    3. Change the base class in MyRibbon.xaml.cs:

      public partial class MyRibbon : System.Windows.Controls.Ribbon.Ribbon
      {
          public MyRibbon()
          {
              InitializeComponent();
          }
      }
      
    4. Add the control to your Main.xaml:

      <local:MyRibbon />
      

    enter image description here