c# - 如何在 xaml 中定义和使用资源以便它们可以在 C# 中使用

标签 c# wpf xaml resources

理论上,我认为我可以在 xaml 文件中定义 Brushes 和 Colors 等,然后将其分配给 c# 中的 button.background。但是我该怎么做呢?我应该在哪里放置我的 lineargradientbrush 定义:

<LinearGradientBrush x:Key="BlaBrush">
                <GradientStop Offset="0" Color="Red"/>
                <GradientStop Offset="1" Color="Green"/>
</LinearGradientBrush>

只是将它放在我窗口的 xaml 文件中的不同位置会导致各种错误消息:/

我在 stackoverflow 上发现了这个问题:How to use a defined brush resource in XAML, from C# which 解释了一部分,不过他好像知道去哪里做Brush定义。

我还尝试将 shinyblue.xaml wpf 模板添加到应用程序并添加了 <ResourceDictionary Source="ShinyBlue.xaml"/>到 app.xaml 中的 application.resources。这使我所有的按钮立即变成蓝色,但是仍然无法从 C# 访问在 shinyblue.xaml 中定义的“东西”,例如 NormalBrush - 至少我不知道如何访问。

马克

最佳答案

您的 xaml 看起来像这样:

主窗口.xaml

<Window x:Class="BrushResource.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">

<Window.Resources>
    <LinearGradientBrush x:Key="BrushOne" StartPoint="0,0.5" EndPoint="1,0.5" Opacity="0.5">
        <LinearGradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="Black" Offset="0" />
                <GradientStop Color="Silver" Offset="1" />
            </GradientStopCollection>
        </LinearGradientBrush.GradientStops>
    </LinearGradientBrush>

    <LinearGradientBrush x:Key="BrushTwo" StartPoint="0,0.5" EndPoint="1,0.5" Opacity="0.5">
        <LinearGradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="Maroon" Offset="0" />
                <GradientStop Color="Silver" Offset="1" />
            </GradientStopCollection>
        </LinearGradientBrush.GradientStops>
    </LinearGradientBrush>
</Window.Resources>

<StackPanel>
    <Button Content="Button" Width="100" Click="myButton_Click"/>
</StackPanel>

要赋值,需要像这样从资源中抓取渐变画笔:

主窗口.xaml.cs

private void myButton_Click(object sender, RoutedEventArgs e)
    {
        (sender as Button).Background = this.Resources["BrushOne"] as LinearGradientBrush;
    }

关于c# - 如何在 xaml 中定义和使用资源以便它们可以在 C# 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3308868/

相关文章:

xaml - Xamarin(框架。)GestureRecognizers 不起作用

c# - 将另一个构建排队,然后等待构建完成

.net - 翻译 WPF

c# - 如何深拷贝一个实体

c# - 在 C#、WPF、MVVM 中更改标签的颜色

wpf - MahApps Metro 捕获关闭窗口事件

c# - WPF : ListBox SelectedItems not updating or being accumulated when selection changed

silverlight - 在自定义控件中使依赖属性绑定(bind)两种方式

c# - 使用 WinForms 在 C# 中为 TableLayoutPanel 创建动态 Controller 名称

c# - 在 WPF 中使用 PrintDialog 打印 Canvas