从理论上讲,我认为我可以在xaml文件中定义笔刷和颜色等,并将其分配给c#中的button.background。但是我该怎么做呢?我应该把我的线性梯度笔刷定义放在哪里呢?
<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#上发现了这个问题,它解释了其中的一部分,但他似乎知道在哪里做画笔定义。
我还尝试将shinyblue.xaml wpf模板添加到应用程序中,并将<ResourceDictionary Source="ShinyBlue.xaml"/>
添加到app.xaml中的application.resources中。这让我所有的按钮立即变成蓝色,但仍然无法从C#访问在shinyblue.xaml中定义的“东西”,比如NormalBrush --至少我不知道是如何访问的。
Marc
发布于 2010-07-22 20:48:52
您的xaml将如下所示:
MainWindow.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>
要赋值,需要从资源中抓取渐变笔刷,如下所示:
MainWindow.xaml.cs
private void myButton_Click(object sender, RoutedEventArgs e)
{
(sender as Button).Background = this.Resources["BrushOne"] as LinearGradientBrush;
}
发布于 2010-07-22 20:51:41
请注意,现有的答案谈到了将资源放在Window.Resources中。如果您希望资源在应用程序范围内可用,您可以考虑将它们放在App.xaml中,或者更好的是,创建独立的资源字典,这些字典可以包含在您的视图中并在其他地方(包括其他项目)重用
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="DefaultStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
<Style x:Key="my_style" />
</ResourceDictionary>
</UserControl.Resources>
发布于 2010-07-22 20:43:56
将它们放在XAML中某个元素的Resources集合中:
<Window ...>
<Window.Resources>
<LinearGradientBrush x:Key="BlaBrush">
<GradientStop Offset="0" Color="Red"/>
<GradientStop Offset="1" Color="Green"/>
</LinearGradientBrush>
<!-- Other resources -->
</Window.Resources>
<!-- Contents of window -->
</Window>
然后使用FindResource在代码中获取它们
var blaBrush = this.FindResource("BlaBrush") as LinearGradientBrush;
有关详细信息,请参阅Resources Overview。
https://stackoverflow.com/questions/3308868
复制相似问题