制作一个按钮资源并在多个地方使用它
Make a Button resource and use it in multiple places
如何定义全局 按钮 并在 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
,如果我定义它正确如何在 CodeBehind 和 XAML 中使用它.
在你的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 应用程序。这样做使得从代码背后访问控件的需求已经过时,可能值得您研究一下。
在您的 App.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 = this.FindResource("Attach") as Style;
Button.Style = style;
如何定义全局 按钮 并在 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
,如果我定义它正确如何在 CodeBehind 和 XAML 中使用它.
在你的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 应用程序。这样做使得从代码背后访问控件的需求已经过时,可能值得您研究一下。
在您的 App.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 = this.FindResource("Attach") as Style;
Button.Style = style;