创建一个Button资源,并在多个地方使用它



如何定义一个全局按钮并在WPF中的多个位置使用它。

这是我的按钮按钮,我想在多个地方使用它。

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

然而,我试图在App.xaml (Application.Resources)

中定义它

MainWindow.xaml (Window.Resources内部)

但是我不能访问CodeBehind

 Button button = Resources["Attach"];

我的问题是在哪里定义我的button,如果我定义它正确如何使用它在CodeBehindXAML

在您的应用程序。xaml你必须添加和定义你想要的按钮样式。

<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>
要在代码中访问它,你需要初始化一个新的样式对象,并用你在App.xaml中创建的样式填充它。最后,将新样式添加到按钮的style属性中。
Style style = this.FindResource("Attach") as Style;
Button.Style = style;

在你的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>

在你的按钮布局中定义一个HiercharchicalDataTemplate将允许你在你的TreeView中重复使用它作为ItemTemplate:

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

正如你所看到的,我正在大量使用资源绑定和数据绑定,因为我正在以MVVM方式构建我的wpf/sl应用程序。这样做使得从代码后面访问控件的需求过时了,可能值得您研究一下。

最新更新