Make a Button resource and use it in multiple places

479 Views Asked by At

how can i define a global button and use it in multiple places in WPF.

here is my button witch i want to use it in multiple places.

<Button x:Key="Attach" Width="90" Margin="220,0,0,0" Content="Attach" Height="16" FontSize="11"/>

however i tried to define it in App.xaml(Application.Resources)

and also in MainWindow.xaml (inside Window.Resources)

But i cannot access it in CodeBehind

 Button button = Resources["Attach"];

My question is where to define my button and if i defined it correct how to use it in CodeBehind and XAML.

2

There are 2 best solutions below

0
On BEST ANSWER

In your MainWindow.xaml

<Window.Resources>
    <HierarchicalDataTemplate 
        x:Key="TreeViewMainTemplate" 
        ItemsSource="{Binding SubTopics}">
        <Button 
            Width="90" 
            Margin="220,0,0,0" 
            Content="Attach" 
            Height="16" 
            FontSize="11" />
    </HierarchicalDataTemplate>
</Window.Resources>

Defining a HiercharchicalDataTemplate with your button layout will allow you to re-use it as an ItemTemplate in your TreeView:

<TreeView 
    Name="TopicTreeView" 
    ItemsSource="{Binding Topics}" 
    ItemTemplate="{StaticResource TreeViewMainTemplate}">
</TreeView>

As you see I'm making intensive use of binding for resources as well as data because I'm building my wpf/sl apps the MVVM way. Doing so makes the need to access controls from code behind obsolete and might be worth looking into for you.

0
On

In your App.xaml you will have to add and define a style that you want for your buttons.

<Application.Resources>
        <Style x:Key="Attach" TargetType="{x:Type Button}">
            <Setter Property="Height" Value="16" />
            <Setter Property="Width" Value="90" />
            <Setter Property="Content" Value="Attach" />
            <Setter Property="Margin" Value="220,0,0,0" />
            <Setter Property="FontSize" Value="11" />
        </Style>
</Application.Resources>

And to access it in your code-behind you will need to initialize a new style object and populate it with the style you created in your App.xaml. Lastly just add that new style to the style property of your button.

Style style = this.FindResource("Attach") as Style;
Button.Style = style;